[英]Trait type parameters inference
为什么Scala编译器不能将Y
的类型参数A
推断为Int
?
trait X[A]
trait Y[A] extends X[A]
object Foo extends X[Int] with Y
有没有一种方法可以让Y
知道X
的类型参数,而无需在Foo
的声明中两次指定它呢? 我也无法获得自动键入解决方案。
对于某些用例,使用中间类可以解决问题:
import scala.reflect.runtime.universe._
abstract class XBase {
type A
def say(a : A) : Unit = println(a)
}
trait Y extends XBase {
override def say(a : A) : Unit = {
println("Hello ")
super.say(a)
}
}
class X[B : TypeTag] extends XBase {
type A = B
}
object Foo extends X[Int] with Y
Scala不支持在类型声明中推断(和忽略)类型构造函数参数。 在将来的基于DOT演算的Scala版本中,尝试统一类型参数和类型成员是可能的。
例如,参见Odersky的演讲“类型的麻烦”的幻灯片(幻灯片29ff)。
您是否需要这种形式的类型参数? 在某些情况下,可以使用以下解决方案:
trait X { type A /* type parameter as member */ }
trait Y extends X
object Foo extends Y { type A = Int /* equivalent to Y[Int] or X [Int] */ }
它可以在定义中使用。
trait X {
type A
def xfun: A
}
trait Y extends X { def tuple[K](k: K): (K, A) = (k -> xfun) }
object Foo extends Y {
def xfun = System.identityHashCode(this)
type A = Int
}
然后如果测试:
scala> Foo.tuple("test")
res0: (String, Foo.A) = (test,2088931356)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.