在scala中获取单例类型的实例

时间:2019-02-20 12:10:20

标签: scala singleton-type

我想在Scala中获得单例类型的实例,这可能吗?

示例:(我知道在这种情况下可以更轻松地完成操作

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
}

2 个答案:

答案 0 :(得分:2)

也许您想要类似的东西

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
}

答案 1 :(得分:2)

使用shapeless.Witness正确的语法是

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)

不幸的是,在当前版本的Shapeless(2.3.3)中,存在一个错误,并且该代码无法编译。但是在fix之后。