gpt4 book ai didi

scala - 含糊不清的隐含

转载 作者:行者123 更新时间:2023-12-04 06:10:20 25 4
gpt4 key购买 nike

问题是为什么下面的代码不能用于类型推断(下面是一个 REPL session 来演示),它可以修复吗?更具体地说,这与编译器用来推断返回类型的 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) 中有这个 session :
scala> :load c:\temp\UrlTest.scala
Loading c:\temp\UrlTest.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] {

关于scala - 含糊不清的隐含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5391533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com