【问题标题】:case classes return Product instead of actual type案例类返回产品而不是实际类型
【发布时间】:2013-10-08 19:40:31
【问题描述】:

我有一个特征和一些扩展这个特征的案例类。

sealed trait Bird
case class Eagle(age: Int) extends Bird
case class Sparrow(price: Double) extends Bird

如果我做任何我希望将 Trait 作为类型返回的事情,例如

val result = "test" match {
  case s:String if s startsWith "t" => Eagle(5)
  case _ => Sparrow(2)
}

我得到了这个 Product 类型。

> result: Product with Serializable with Bird = Eagle(5)

我知道Product 是所有案例类都扩展的东西。但是我不处理Product,我怎样才能得到Bird甚至Eagle呢?

【问题讨论】:

    标签: scala case-class


    【解决方案1】:

    您可以忽略您不关心的方面。 result Bird,所以把它当作一个。它也是 ProductSerializable 是不相关的(除非你想要/需要它)。您可以通过指定其预期类型使其显式:

    val result: Bird = "test" match {
      case s:String if s startsWith "t" => Eagle(5)
      case _ => Sparrow(2)
    }
    

    给予:

    result: Bird = Eagle(5)
    

    或者,您可以将其分配给Bird 类型的另一个变量,或者只是期望它是Bird 并提前充电,调用在Bird 特征上定义的方法,将其作为参数传递给函数取Bird等类型的参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-17
      • 2018-11-19
      • 2021-03-11
      • 2014-04-02
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多