误用 Scala 或 Eclipse 使用隐式错误
我有一个类定义如下:
class NDArray[T](data: List[List[T]])(implicit num: Numeric[T])
.....
我有一个创建并返回新 NDArray 的对象:
object Foo
{
def apply() =
{
new NDArray(List(List())
}
}
我收到以下错误: 构造函数 NDArray 的参数不足:(隐式 num:Numeric[A])com.numscal.matrix.NDArray[A]。未指定值参数 num。
我尝试在创建 NDArray 的对象中导入 Numeric,但这不起作用。我的 NDArray 单元测试不导入 Numeric,并且没有任何问题。
我对发生的事情感到困惑。有什么想法吗?
I have a Class defined below:
class NDArray[T](data: List[List[T]])(implicit num: Numeric[T])
.....
I have an object that creates and returns a new NDArray:
object Foo
{
def apply() =
{
new NDArray(List(List())
}
}
I am getting the following error:
not enough arguments for constructor NDArray: (implicit num: Numeric[A])com.numscal.matrix.NDArray[A]. Unspecified value parameter num.
I've tried importing Numeric in the object that creates the NDArray, but that doesn't work. My unit tests for NDArray don't import Numeric and they don't have any issues.
I am confused as to what is going on. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
data
是T
类型的列表的列表。NDArray
的构造函数需要一个Numeric[T]
类型的对象。由于该参数被声明为隐式
,这意味着当编译器可以在当前可见范围内找到一个也被定义为隐式
的参数时,您无需显式指定该参数。 >。现在,由于您创建了
NDArray
实例而未指定T
,编译器会推断T
。它找到列表的列表,并使用内部列表的元素类型作为T
。但由于您没有指定该列表并且列表为空,因此默认为List[Nothing]
,因此编译器得出结论T
是类型什么都没有
。然后,它搜索
Numeric[Nothing]
的隐式
实例,但该实例不存在。您可以做几件事。要么:
要么:(
虽然我不确定最后一个是否会起作用。我不知道编译器是否会正确推断内部列表的类型参数;你只需要尝试一下。
)默认情况下已导入
Numeric[Int]
的隐式 实例,因为它是Predef
的一部分。您不需要显式导入它。所有原始数字类型也是如此。我不知道你是否想使用整数列表、浮点数列表或其他什么。编译器也不知道,并且无法推断,因为您给出的列表是空的。
data
is a list of lists of typeT
. The constructor ofNDArray
requires an object of typeNumeric[T]
. Because that parameter is declaredimplicit
, that means that you don't need to specify one explicitly when the compiler can find one in the currently visible scope that also has been defined asimplicit
.Now, since you create an instance of
NDArray
without specifyingT
, the compiler infersT
. It finds the list of lists, and uses the element type of the inner list asT
. But since you did not specify that one and the list is empty, this defaults to being aList[Nothing]
, therefore, the compiler concludes thatT
is the typeNothing
.Then it searches for an
implicit
instance ofNumeric[Nothing]
, but that does not exist.There are several things you can do. Either:
Or:
(Although I'm not sure if that last one is gonna work. I don't know if the compiler will infer the type parameter of the inner list correctly; you just have to try it.)
The
implicit
instance ofNumeric[Int]
is already imported by default, since it is part ofPredef
. You don't need to import it explicitly. The same goes for all primitive numeric types.I don't know if you want to use a list of lists of integers, or floats, or whatever. The compiler does not know either, and it can't infer because the list you have given is empty.
Nothing
没有隐式数值,请使用List.empty[List[TypeYouNeed]]
There is no implicit Numeric for
Nothing
, useList.empty[List[TypeYouNeed]]