当显式转换有效时,为什么这个 Scala 隐式转换会失败? [英] Why does this Scala implicit conversion fail when explicit conversion works?

查看:56
本文介绍了当显式转换有效时,为什么这个 Scala 隐式转换会失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么即使显式调用函数有效,以下隐式转换也无效?

Why doesn't the following implicit conversion work even though explicitly calling the function works?

scala> implicit def view[A, C](xs: C)(implicit ev: C <:< Iterable[A]) = new { def bar = 0 } 
view: [A, C](xs: C)(implicit ev: <:<[C,scala.collection.immutable.Iterable[A]])java.lang.Object{def bar: Int}

scala> List(1) bar
<console>:147: error: Cannot prove that List[Int] <:< scala.collection.immutable.Iterable[A].
              List(1) bar
                  ^

scala> view(List(1)) bar
res37: Int = 0

推荐答案

简而言之,正如错误消息所暗示的那样,它无法推断 A.编译器无法使用任何信息来推断 A 必须是什么,因此它必须假设它可以是任何东西.

Simply put, as the error message suggests, it cannot infer A. There's no information the compiler can use to infer what A must be, so it must assume it can be anything.

您可能会反驳说它可以从 C <:< 推断 AIterable[A] ,但这会将问题彻底解决:它不会使用 <:< 来检查约束,而是使用约束来推断 一个!这个逻辑不合理.

You might retort that it can infer A from C <:< Iterable[A], but that would turn the problem on its head: instead of using <:< to check constraints, it would use the constraints to infer the type of A! That logic is not sound.

这篇关于当显式转换有效时,为什么这个 Scala 隐式转换会失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆