Question

I have a trait and a few case classes extending this trait.

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

If I do a anything that I would expect to return the Trait as a type, like

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

I get instead this Product type.

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

I understand Product is something that all case classes extend. But I don't what to deal with Product, how can I get Bird or even Eagle back instead?

Was it helpful?

Solution

You can just ignore the aspects you don't care about. result is a Bird, so use it as one. That it is also a Product and a Serializable is not relevant (unless you want/need it to be). You can make it explicit by specifying its expected type:

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

Gives:

result: Bird = Eagle(5)

Or, you can assign it to another variable of type Bird, or simply expect it to be a Bird and charge ahead, calling methods defined on the Bird trait, passing it as an argument to a function taking a parameter of type Bird, etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top