【发布时间】:2019-06-18 13:29:32
【问题描述】:
我有一段相当简单的代码无法编译,因为显然无法推断出类型。我想了解为什么它没有,因为我有很多类型注释,它应该可以工作。代码是
object MyApp {
trait A {
type V
val value: V
}
case class ConcreteA(value: Int) extends A { type V=Int }
def convert[T<:A](v: T#V): T = ConcreteA(v.asInstanceOf[Int]).asInstanceOf[T] // brief method with casts for illustration purposes only
def main(args: Array[String]) {
val i: Int = 10
val converted: ConcreteA = convert(i)
}
}
(如果我在 convert-call 上添加明确的 [ConcreteA],它会编译)
我得到的错误是
MyApp.scala:19: error: no type parameters for method convert: (v: T#V)T exist so that it can be applied to arguments (Int)
--- because ---
argument expression's type is not compatible with formal parameter type;
found : Int
required: ?T#V
val converted: ConcreteA = convert(i)
^
MyApp.scala:19: error: type mismatch;
found : Int
required: T#V
val converted: ConcreteA = convert(i)
^
MyApp.scala:19: error: type mismatch;
found : T
required: MyApp.ConcreteA
val converted: ConcreteA = convert(i)
^
three errors found
谁能给我解释一下?
编辑:我希望 Scala 在这里推断出 T 是 ConcreteA。我这样做是因为convert 调用的结果进入了这样注释的 val 类型。
【问题讨论】:
标签: scala type-inference