Scala:类参数中的抽象类型

duc*_*thd 4 types scala

很简单,有没有办法结合构造函数参数和抽象类型?例如,我想做的事情

class A(t: Seq[T]) {
   type T
}
Run Code Online (Sandbox Code Playgroud)

ret*_*nym 6

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

这是尽可能接近:

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)              
                     ^
Run Code Online (Sandbox Code Playgroud)

  • 他希望有一个与类型成员相同类型的构造函数参数."AA"级非常接近. (2认同)