scala - 了解隐式 < :< parameter

标签 scala implicit

这个例子是我写的

class TestMatch[T](private val t: T){
    def test()(implicit ev: T <:< Option[Int]) = println(ev(t).get)
}

及其测试

val tm = TestMatch(Some(10))
tm.test() //fine

val tm2 = TestMatch(10)
tm2.test() //compilation error

问题是谁创建了 implicit ev: T <:< Option[Int]当我调用test时方法?我知道我没有。也许编译器知道 implicit <:<并知道如何处理它。

<:< 的文档不太清楚

To constrain any abstract type T that's in scope in a method's argument list (not just the method's own type parameters) simply add an implicit argument of type T <:< U, where U is the required upper bound; or for lower-bounds, use: L <:< T, where L is the required lower bound.

这是否意味着编译器将自行承担剩下的工作?我只是添加 implicit ev: T1 <:< T2

最佳答案

第一个代码段会因为 Predef.identity 进行编译,这意味着您始终可以将类型 T 隐式转换为类型 T(在本例中) 选项[Int])。否则,您需要自己将隐式引入作用域。

关于scala - 了解隐式 < :< parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38943624/

相关文章:

scala - 无法在单例对象中找到隐式值

scala - 给出/使用 Scala 2 隐式和 Scala 3 之间的区别

Scala:类型模式匹配期间的前向引用错误

mongodb - 在 Worker 的帮助下从 Spark 读取巨大的 MongoDB 集合

string - Scala 中的条件隐式函数

c# - 如何检查类型之间是否存在隐式转换?

scala - Scala 中带有隐式参数的函数类型

algorithm - Scala 中的合并排序

scala - 三元运算符类似于 ? :

database - 将 Squeryl 和 H2 数据库用于桌面应用程序的性能问题