duckworthd
duckworthd

Reputation: 15197

Scala: Abstract Types in Class Parameters

Quite simply, is there any way to marry constructor arguments and abstract types? For example, something I would like to do

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

Upvotes: 4

Views: 262

Answers (2)

jwinder
jwinder

Reputation: 378

Does this not suit your needs?

class A[T](ts: Seq[T])

Upvotes: 2

retronym
retronym

Reputation: 55028

The members of the class aren't in scope in the parameter declaration of the constructor.

This is as close as you can get:

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)              
                     ^

Upvotes: 6

Related Questions