为什么类型会导致“带有动物可序列化的产品”而不是动物?

时间:2019-06-07 05:32:23

标签: scala types

假设我有

val flag = true

为什么类型会导致Product with Serializable with Animal而不是Animal

class Animal(name : String)
case class Herbivore(name : String) extends Animal(name)
case class Carnivore(name : String) extends Animal(name)

val cow = new Herbivore("cow")
val tiger = new Carnivore("tiger")

if (flag) cow else tiger // Why is type Product with Serializable with Animal? 

1 个答案:

答案 0 :(得分:7)

案例类automatically extend Product with Serializable

class Animal(name : String)
case class Herbivore(name : String) extends Animal(name)
case class Carnivore(name : String) extends Animal(name)

实际上是

class Animal(name : String)
case class Herbivore(name : String) extends Animal(name) with Product with Serializable
case class Carnivore(name : String) extends Animal(name) with Product with Serializable

因此,if (flag) cow else tiger表达式编译器可以推断的最精确类型是Product with Serializable with Animal。如果我们从案例类更改为像这样的类

class Animal(name : String)
class Herbivore(name : String) extends Animal(name)
class Carnivore(name : String) extends Animal(name)

然后,if-else表达式的推断类型确实为Animal

按照@TravisBrown的建议,像这样使ADT根扩展Product with Serializable

abstract class Animal(name : String) extends Product with Serializable
case class Herbivore(name : String) extends Animal(name)
case class Carnivore(name : String) extends Animal(name)

将if-else表达式的推断类型也设为Animal