作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
此代码编译并执行预期的操作
class MyList[T](list: T)(implicit o: Ordering[T])
但是这不会:
class MyList2[T](list: T) {
val o = implicitly[Ordering[T]]
}
我不明白为什么。在第一个示例中,当构造类时,编译器会发现 Ordering 是隐式的,因为它知 Prop 体类型 T
。但在第二种情况下,它也应该找到隐含的,因为 T
已经是一个具体类型。
最佳答案
In the first example when the class is being constructed the compiler will find the Ordering implicit because it will know the concrete type T.
在第一个示例中,编译器需要在范围内有一个隐式的 Ordering[T]
才能找到它。编译器本身不会“弥补”隐式。由于您直接要求通过第二个参数列表提供一个,如果存在这样的隐式,它将被传递给类构造函数。
But in the second case it should also find the implicit since
T
will already be a concrete type.
T
在编译时是具体类型这一事实并不能帮助编译器找到它的隐含类型。当我们说 T
是具体类型时,您必须记住,在调用点,T
只是一个泛型类型参数,仅此而已。如果你不帮助编译器,它就不能保证在范围内具有隐式。您需要让该方法提供一个隐含的方法,这可以通过 Context Bound 来完成:
class MyList2[T: Ordering](list: T)
这需要在编译时存在类型 T
的排序。从语义上讲,这等同于您的第二个参数列表。
关于scala - 通过方法/构造函数参数隐式与隐式使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40022157/
我是一名优秀的程序员,十分优秀!