scala – 泛型类型的隐式转换?
发布时间:2020-12-16 19:16:29 所属栏目:安全 来源:网络整理
导读:考虑到这个功能: def justTrue[T,S](seq: S)(implicit ev: S : Seq[T]) = truejustTrue(List(1,2,3)) true 有用.但为什么不能将相同的签名用作隐式转换? implicit class TruthTeller[T,S](seq: S)(implicit ev: S : Seq[T]) { def justTrue = true}List(1,
考虑到这个功能:
def justTrue[T,S](seq: S)(implicit ev: S <:< Seq[T]) = true justTrue(List(1,2,3)) >> true 有用.但为什么不能将相同的签名用作隐式转换? implicit class TruthTeller[T,S](seq: S)(implicit ev: S <:< Seq[T]) { def justTrue = true } List(1,3).justTrue >> error: Cannot prove that List[Int] <:< Seq[T]. 隐式转换只是一个函数吗? 解决方法
你是完全正确的,这应该在隐式def / class中也能正常工作.
这是一个错误,其中类型参数意外地从隐式视图的参数中存在类型推断: SI-7944: type variables escape into the wild 它现在固定为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,3).justTrue // Exiting paste mode,now interpreting. defined class TruthTeller res0: Boolean = true 至于变通方法,有很多,你可以在你的答案中使用更高级的,或者例如从seq参数强制推断T: // 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,3).justTrue (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |