Reputation: 4231
I am trying to get proper type with a typed function e.g
sealed trait Pet
case object Dog extends Pet
case object Cat extends Pet
case object Fish
def getPet[P >: Pet](pet: P) : P = {
pet match{
case Dog => Dog
case Cat => Cat
}
}
val d: Dog = getPet(Dog)//not compiled
any ideas ?
Upvotes: 0
Views: 57
Reputation: 48410
Here is a typeclass example
sealed trait Pet
case object Dog extends Pet
case object Cat extends Pet
case object Fish extends Pet
trait PetFactory[P <: Pet] {
def getPet(p: P): P
}
object PetFactory {
def getPet[P <: Pet](p: P)(implicit petFactory: PetFactory[P]): P = petFactory.getPet(p)
implicit val dogFactory: PetFactory[Dog.type] = (dog: Dog.type) => dog
implicit val catFactory: PetFactory[Cat.type] = (cat: Cat.type) => cat
implicit val fishFactory: PetFactory[Fish.type] = (fish: Fish.type) => fish
}
import PetFactory._
getPet(Dog)
getPet(Cat)
getPet(Fish)
which outputs
res0: Dog.type = Dog
res1: Cat.type = Cat
res2: Fish.type = Fish
Note that the type of singleton object O
is O.type
, for example
val fish: Fish.type = Fish
Upvotes: 6