为什么在需要 RichLong 超类型的情况下不应用从 Long 到 RichLong 的隐式转换?
Scala 2.8 规范在第 7.3 节中说(突出显示是我的):
隐式参数和方法还可以定义称为视图的隐式转换。 从类型 S 到类型 T 的视图由具有函数类型的隐式值定义 S=>T或(=>S)=>T或者通过可转换为该类型的值的方法。 视图在两种情况下应用。
- 如果表达式 e 属于 T 类型,并且 T 不符合表达式的 预期类型 pt。在这种情况下,搜索隐式 v,适用于 e 且其结果类型符合 pt。搜索将按照以下情况进行 隐式参数,其中隐式范围是 T => 之一角如果有这样一个 找到视图,表达式 e 转换为 v(e)。
[...]
鉴于上述和以下事实:
Long
不是java.lang.Comparable[Long]
的子类型,即不符合< /strong> 键入T
,其中T <: java.lang.Comaparable[Long]
Predef
包含隐式 def longWrapper (x : Long) : RichLong
RichLong
是java.lang.Comparable[Long]
的子类型,即符合类型T
其中T <: java.lang.Comaparable[Long]
我希望在遇到 Long
且其子类型为预期为 java.lang.Comparable[Long]
。但是:
scala> def test[T <: java.lang.Comparable[Long]](c: T) = println(c)
test: [T <: java.lang.Comparable[Long]](c: T)Unit
scala> test(12L)
<console>:7: error: inferred type arguments [Long] do not conform to method test's type parameter bounds [T <: java.lang
.Comparable[Long]]
test(12L)
^
如果显式转换值,结果符合预期:
scala> test(longWrapper(12L))
12
为什么不隐式应用转换函数?
Scala 2.8 spec says in section 7.3 (highlighting is mine):
Implicit parameters and methods can also define implicit conversions called views.
A view from type S to type T is defined by an implicit value which has function type
S=>T or (=>S)=>T or by a method convertible to a value of that type.
Views are applied in two situations.
- If an expression e is of type T, and T does not conform to the expression’s
expected type pt. In this case an implicit v is searched which is applicable to
e and whose result type conforms to pt. The search proceeds as in the case of
implicit parameters, where the implicit scope is the one of T => pt. If such a
view is found, the expression e is converted to v(e).[...]
given the above and the following facts:
Long
is not a subtype ofjava.lang.Comparable[Long]
, i.e. does not conform to typeT
whereT <: java.lang.Comaparable[Long]
Predef
containsimplicit def longWrapper (x: Long) : RichLong
RichLong
is a subtype ofjava.lang.Comparable[Long]
, i.e. conforms to typeT
whereT <: java.lang.Comaparable[Long]
I would expect the implicit conversion to be applied where Long
is encountered and a subtype of java.lang.Comparable[Long]
is expected. However:
scala> def test[T <: java.lang.Comparable[Long]](c: T) = println(c)
test: [T <: java.lang.Comparable[Long]](c: T)Unit
scala> test(12L)
<console>:7: error: inferred type arguments [Long] do not conform to method test's type parameter bounds [T <: java.lang
.Comparable[Long]]
test(12L)
^
The result is as expected if the value is converted explicitly:
scala> test(longWrapper(12L))
12
Why isn't the conversion function applied implicitly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用视图绑定 (
<%
) 来让编译器查找并应用隐式转换。您可以在此页面上阅读有关视图绑定的更多信息(Ctrl+F “视图绑定”)。
You need to use a view-bound (
<%
) to have compiler look for and apply the implicit conversion.You can read more about view-bound on this page (Ctrl+F for "view bound").