score:4

Accepted answer

Using shapeless you can write:

import shapeless._

class SpecificAnimalContainer[A <: Animal](a: A)(implicit ev: A =:!= Animal) {
  def specificAnimal: A = a
}

//  val animalContainer = new SpecificAnimalContainer[Animal](new Animal)// doesn't compile

Otherwise you can implement similar type for implicit yourself.

Type constraint for type inequality in scala

Enforce type difference

How can I have a negation type in Scala?

score:0

It's a bit unclear what you're trying to achieve, but your problem looks exactly like a book example from Scala documentation at https://docs.scala-lang.org/tour/upper-type-bounds.html

abstract class Pet extends Animal {}

class PetContainer[P <: Pet](p: P) {
  def pet: P = p
}

class Lion extends Animal {
  override def name: String = "Lion"
}

//  val lionContainer = new PetContainer[Lion](new Lion)
//                         ^this would not compile

Hope this helps


Related Query

More Query from same tag