Lai*_*uan 7 scala implicit-conversion
考虑到这个功能:
def justTrue[T, S](seq: S)(implicit ev: S <:< Seq[T]) = true
justTrue(List(1,2,3))
>> true
Run Code Online (Sandbox Code Playgroud)
有用.但是为什么不能将相同的签名用作隐式转换?
implicit class TruthTeller[T, S](seq: S)(implicit ev: S <:< Seq[T]) {
def justTrue = true
}
List(1,2,3).justTrue
>> error: Cannot prove that List[Int] <:< Seq[T].
Run Code Online (Sandbox Code Playgroud)
隐式转换只是一个函数吗?
你是完全正确的,这应该在隐式def/中也能正常工作class.
这是一个错误,其中类型参数意外地从隐式视图的参数中存在类型推断:
它现在固定为2.11.0-M7:
Welcome to Scala version 2.11.0-M7 (OpenJDK 64-Bit Server VM, Java 1.7.0_45).
Type in expressions to have them evaluated.
Type :help for more information.
scala> :pa
// Entering paste mode (ctrl-D to finish)
implicit class TruthTeller[T, S](seq: S)(implicit ev: S <:< Seq[T]) {
def justTrue = true
}
List(1,2,3).justTrue
// Exiting paste mode, now interpreting.
defined class TruthTeller
res0: Boolean = true
Run Code Online (Sandbox Code Playgroud)
至于变通方法,有很多,你可以在你的答案中使用更高级的,或者例如T从seq参数强制推断:
// the implicit ev isn't even needed here anymore
// but I am assuming the real use case is more complex
implicit class TruthTeller[T, S](seq: S with Seq[T])(implicit ev: S <:< Seq[T]) {
def justTrue = true
}
// S will be inferred as List[Int], and T as Int
List(1,2,3).justTrue
Run Code Online (Sandbox Code Playgroud)