繁体   English   中英

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

[英]Get instance of singleton type in scala

我想在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
}

也许你想要类似的东西

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
}

使用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)中,存在一个错误,并且该代码无法编译。 但是修复之后就可以了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM