【发布时间】:2012-07-02 21:07:31
【问题描述】:
我想定义一个用T 类型参数化的方法,它的行为取决于可以找到Box[T] 类型的隐式参数。以下代码将此方法定义为foo。当使用foo[Int] 或foo[String] 调用时,它将按预期返回1 或"two"。
事情变得奇怪的地方是方法栏。它被定义为返回Int,但我只有foo 而不是foo[Int]。我希望编译器会推断出T 必须是Int 类型。它没有这样做,而是失败了:
bash $ scalac Code.scala
Types.scala:15: error: ambiguous implicit values:
both value one in object Main of type => Main.Box[Int]
and value two in object Main of type => Main.Box[java.lang.String]
match expected type Main.Box[T]
def bar: Int = foo
^
one error found
是什么导致了这个错误?将 foo 替换为 foo[Int] 可以正常编译。没有 Box[T] 类型的更简单的情况也可以正常编译。该示例也在下面,并使用argle 和bargle 而不是foo 和bar。
object Main extends Application {
case class Box[T](value: T)
implicit val one = Box(1)
implicit val two = Box("two")
def foo[T](implicit x: Box[T]): T = {
x.value
}
// does not compile:
// def bar: Int = foo
// does compile
def bar: Int = foo[Int]
println(bar)
// prints 1
// the simpler situation where there is no Box type
implicit val three = 3
implicit val four = "four"
def argle[T](implicit x: T): T = x
def bargle: String = argle
println(bargle)
// prints "four"
}
在导致这种行为的这个 sn-p 中发生了什么?隐式参数、类型推断和擦除之间的这种交互会导致问题吗?有没有办法修改此代码以使def foo: Int = bar 行有效?
【问题讨论】:
标签: scala type-inference implicit type-erasure