Scala:类参数中的抽象类型

前端之家收集整理的这篇文章主要介绍了Scala:类参数中的抽象类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
很简单,有没有办法结合构造函数参数和抽象类型?例如,我想做的事情

class A(t: Seq[T]) {
   type T
}

解决方法

该类的成员不在构造函数的参数声明中.

这是尽可能接近:

scala> trait T { type T; val a: T }
defined trait T

scala> def A[X](x: X) = new T { type T = X; val a = x }
A: [X](x: X)Object with T{type T = X}

scala> A[Int](0)
res0: Object with T{type T = Int} = $anon$1@3bd29ee4

scala> A[String](0)
<console>:10: error: type mismatch;
 found   : Int(0)
 required: String
              A[String](0)
                        ^
scala> class AA[X](val a: X) extends T { type T = X }
defined class AA

scala> new AA[Int](0)
res5: AA[Int] = AA@1b3d4787

scala> new AA[String](0)
<console>:10: error: type mismatch; 
  found   : Int(0) 
  required: String              
      new AA[String](0)              
                     ^

猜你在找的Scala相关文章