[英]Scala implicit conversion for type aliases
限定
type TA[T] = T => Int
implicit class TAOps[T](a: TA[T]) {
def foo(): Unit = {println("TA")}
}
val ta: TA[Double] = x => x.toInt
现在,
ta.foo()
无法使用消息value foo is not a member of ammonite.$sess.cmd1.TA[Double]
进行编译value foo is not a member of ammonite.$sess.cmd1.TA[Double]
,
而显式调用
TAOps(ta).foo()
打印TA
。 为什么隐式转换在前一种情况下不起作用?
你的隐式def期望一个接收一个类型参数的类型,即TA[T]
你的声明: val ta: TA[Double] = ...
是一个自我类型,不带任何类型参数。 所以编译器不会使用你的隐式def来键入check this。
结论对于采用类型参数的类型,您有一个隐式类型转换,而TA[Double]
不接受任何类型参数。
Function1
: implicit class TAOps[T](a: T => Int) {
def foo: Unit = {
println("TA")
}
}
implicit class TAOps[T](a: ({type Alias = TA[T]})#Alias) {
def foo: Unit = {
println("TA")
}
}
这里你创建的类型是curried。 因此编译器现在将此隐式转换应用于匹配的类型,它不再期望接收1类型参数的类型。
有关Lambda类型的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.