简体   繁体   中英

Scala: How do I set a generic Trait?

I can't set up this generic trait whose parametrized forms can be consumed by a common class/object/method. I have tried different +|-|_ combinations :-)

Update: The first comment below shows that this can work if the Wrapper is also parametrized. Can a non-parametrized Wrapper do the job? Can an object Wrapper do the job? Can some magic combination of +|-|_ and all that give me the same desired result with a non-parametrized Wrapper or object?

case class OldStuff(name: String)
case class NewStuff(id: Int)

trait Poster[T] {
def translate(i: Int):T
}

class NewPoster extends Poster[NewStuff] {
def translate(i: Int):NewStuff = new NewStuff(3)
}

class OldPoster  extends Poster[OldStuff] {
def translate(i: Int):OldStuff = new OldStuff("A" * 3)
}

val old = new OldPoster()
// so far so good

class  Wrapper{
var poster: Poster[_] = null  
def setter(p: Poster[_]) = {poster = p } 
def prepare_input[A]( ) = {
  val i: Int = 5
  println(poster.translate(i))
}
}

val w= new Wrapper()
val old = new OldPoster()
w.setter(old)
scala> w.setter(old)
<console>:58: error: type mismatch;
 found   : OldPoster
 required: Poster[_]
       w.setter(old)

First, I don't see such error with Scala 2.11.

Then, would be better to avoid erasure by Poster[_] :

class Wrapper[T] {
  var poster: Poster[T] = null
  def setter(p: Poster[T]) = {poster = p }
  def prepare_input() = {
    val i: Int = 5
    println(poster.translate(i))
  }
}

val w= new Wrapper[OldStuff]()
val old = new OldPoster()
w.setter(old)

Finally, not using mutability would make the code more predictable against concurrency.

class Wrapper[T](poster: Poster[T]) {
  def prepare_input() = {
    val i: Int = 5
    println(poster.translate(i))
  }
}

val w = new Wrapper(new OldPoster())

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