【问题标题】:Is there any way to describe the type in scala 2 for case classes companion-objects of particular type?对于特定类型的案例类伴生对象,有什么方法可以描述 scala 2 中的类型?
【发布时间】:2022-08-19 20:56:19
【问题描述】:

有没有办法在 scala 中描述特定类型的案例类伴生对象的类型?

例如我有

trait SomeTrait

case class Foo() extends SomeTrait
case class Bar() extends SomeTrait

我需要为 Foo 和 Bar 的伴侣对象获取通用类型 喜欢[Foo.type & Bar.type]

  • 不,没有共同点(有用)除了 AnySingleton 之外的同伴的晚餐类型 - 您可以创建另一个 trait 同伴对象必须扩展或者可能是类型类会更好。
  • 你打算如何使用它?
  • 我只需要删除这个 trait-companion,因为这个模式变得太复杂了。因为我不想产生很多抽象,如果本质上我只需要一个抽象

标签: scala


【解决方案1】:

您可以创建伴随对象将扩展的另一个特征。如果您需要使伴生对象模式匹配,请在它们前面添加case,并出于详尽的原因使它们扩展sealed 的特征:

sealed trait SomeTrait
sealed trait AnotherTrait

case class Foo() extends SomeTrait
case class Bar() extends SomeTrait

case object Foo extends AnotherTrait
case object Bar extends AnotherTrait

例如,您可以查看您的模式匹配的对象,例如:

  def methodName(x: AnotherTrait): String = x match {
    case Foo => "it is Foo singleton"
    case Bar => "it is Bar singleton"
  }

println(methodName(Foo)) // it is Foo singleton

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 2021-05-12
    相关资源
    最近更新 更多