Search code examples
scalaconstructorparameterized

Taking in any parameterized object as an argument to a class constructor


Say I have code like this:

abstract class Animal[T <: Animal[T]] {
  def mateWith(that: T)
}

class Cow extends Animal[Cow] {
  override def mateWith(that: Cow) { println("cow") }
}

class Dog extends Animal[Dog] {
  override def mateWith(that: Dog) { println("dog") }
}

I want to write something like this:

class Caretaker (val pet: Animal) {
  ...
}

but this is invalid, since Animal needs to be parameterized. I could solve this by parameterizing Caretaker:

class Caretaker[T <: Animal[T]](val pet: Animal[T]) {
  ...
}

but this is really unnecessary for what I'm doing.

Is there a better way to do this?


Solution

  • class Caretaker(val pet: Animal[_]) {
        ...
    }