假设我有
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?
答案 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
。