简体   繁体   中英

why the constructor doesn't work with covariance in scala

I have following class definition, C defined to take covariance type parameter +T, and I tried to define another constructor method as a shortcut, but I couldn't make it to work with type T.

class C[+T](val value: T, children: List[C[T]]) {
   def this(value: T) = this(value, Nil)  //it fail with covariant type not allowed here

   def this[U >: T](value: U) = this(value, Nil)//it fail with can't find symbol U

   def replace[U >: T](t: U) = new C(t, children) //it success
}

I thought the the second this should work just like the replace method, but it doesn't. could some one explain what behind this, why replace works but not this? and the right way to do this. thanks.

why replace works but not this?

Constructors can't take type parameters (and that's the message I get in 2.10 instead of can't find symbol U ). But even if they could, replace returns C[U] and the constructor must return C[T] .

and the right way to do this

Make it a method in companion object:

object C {
  def apply[U](value: U) = new C(value, Nil) // note that you no longer need T here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM