dtech
dtech

Reputation: 14060

Get instance of singleton type in scala

I want to get the instance of a singleton type in Scala, is this possible?

Example: (I know it can be done easier in this case)

sealed trait Animal
case object Dog extends Animal
case object Cat extends Animal

trait Person {
  def name: String
  // Is there a "FavoriteAnimal.instance" syntax?
  def mostImportantThings = (FavoriteAnimal.instance, name)
  protected type FavoriteAnimal <: Animal with scala.Singleton
}

case class DogPerson(override val name: String) extends Person {
  override type FavoriteAnimal = Dog.type
}

case class CatPerson(override val name: String) extends Person {
  override type FavoriteAnimal = Cat.type
}

Upvotes: 2

Views: 648

Answers (2)

Dmytro Mitin
Dmytro Mitin

Reputation: 51658

Using shapeless.Witness correct syntax is

sealed trait Animal
case object Dog extends Animal
case object Cat extends Animal

trait Person {
  def name: String
  def mostImportantThings(implicit 
    witness: Witness.Aux[FavoriteAnimal]
  ): (FavoriteAnimal, String) = (witness.value, name)
  protected type FavoriteAnimal <: Animal with scala.Singleton
}

case class DogPerson(override val name: String) extends Person {
  override type FavoriteAnimal = Dog.type
}

case class CatPerson(override val name: String) extends Person {
  override type FavoriteAnimal = Cat.type
}

DogPerson("A Dog Person").mostImportantThings // (Dog, A Dog Person)

Unfortunately in the current version of Shapeless (2.3.3) there is a bug and this code doesn't compile. But after fix it does.

Upvotes: 3

Thilo
Thilo

Reputation: 262504

Maybe you want something like

sealed trait Animal
case object Dog extends Animal
case object Cat extends Animal

trait Person[A <: Animal] {
  def name: String
  def animal: A
  def mostImportantThings = (animal, name)
}

case class DogPerson(override val name: String) extends Person[Dog.type] {
  override val animal = Dog
}

case class CatPerson(override val name: String) extends Person[Cat.type] {
  override val animal = Cat
}

Upvotes: 2

Related Questions