这个例子是我写的
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
, whereU
is the required upper bound; or for lower-bounds, use:L <:< T
, whereL
is the required lower bound.
这是否意味着编译器将自行承担剩下的工作?我只是添加 implicit ev: T1 <:< T2
?
最佳答案
第一个代码段会因为 Predef.identity
进行编译,这意味着您始终可以将类型 T
隐式转换为类型 T
(在本例中) 选项[Int]
)。否则,您需要自己将隐式引入作用域。
关于scala - 了解隐式 < :< parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38943624/