斯卡拉 – 暧昧的暗示
发布时间:2020-12-16 09:00:15 所属栏目:安全 来源:网络整理
导读:问题是为什么下面的代码不能用于类型推断(下面是一个REPL会话来演示),它可以修复吗?更具体地说,这与编译器用于推断返回类型的CanBuildFrom的使用有何不同? 鉴于此代码: object S { import java.net._ trait UrlLike[T] { def url(s: String): T } object
问题是为什么下面的代码不能用于类型推断(下面是一个REPL会话来演示),它可以修复吗?更具体地说,这与编译器用于推断返回类型的CanBuildFrom的使用有何不同?
鉴于此代码: object S { import java.net._ trait UrlLike[T] { def url(s: String): T } object UrlLike { implicit object str extends UrlLike[String]{def url(s: String) = s} implicit object url extends UrlLike[URL]{def url(s: String) = new URL(s)} implicit object uri extends UrlLike[URI]{def url(s: String) = new URI(s)} } trait UrlSupport { val _url: String def url[T : UrlLike]: T = implicitly[UrlLike[T]].url(_url) } } 我在REPL(2.8.1)中有这个会话: scala> :load c:tempUrlTest.scala Loading c:tempUrlTest.scala... defined module S scala> import java.net._ import java.net._ scala> import S._ import S._ scala> new UrlSupport{val _url = "http://example.com"} res0: java.lang.Object with S.UrlSupport = $anon$1@155bd22 scala> res0.url : String <console>:14: error: ambiguous implicit values: both object uri in object UrlLike of type object S.UrlLike.uri and object url in object UrlLike of type object S.UrlLike.url match expected type S.UrlLike[T] res0.url : String ^ scala> res0.url : URL <console>:14: error: ambiguous implicit values: both object uri in object UrlLike of type object S.UrlLike.uri and object url in object UrlLike of type object S.UrlLike.url match expected type S.UrlLike[T] res0.url : URL ^ scala> res0.url[String] res3: String = http://example.com scala> res0.url[URL] res4: java.net.URL = http://example.com 解决方法> trait UrlLike[T] { trait UrlLike[+T] { (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |