Trying to understand an example with the smallest upper limit

Given the following attribute and 2 subclasses:

scala> trait Parent
defined trait Parent

scala> case object Kid extends Parent
defined object Kid

scala> case object Child extends Parent
defined object Child

      

I created a function that returns either Kid

or Child

. But the return type is output Product with Serializable with Parent

.

scala> def f(x: Int) = if (true) Kid else Child
f: (x: Int)Product with Serializable with Parent

      

Then I overwrite the same function, except that I explicitly annotate its type:

scala> def g(x: Int): Parent = if (true) Kid else Child
g: (x: Int)Parent

      

Please explain the f

type of output.

+3


source to share


1 answer


Case objects always inherit from Product

as well as from Serializable

(this is done transparently by the compiler).

Also, both Kid

and Child

explicitly extendParent



Thus, both Kid

and Child

are subtypes Product with Serializable with Parent

. Since they have no other common types, this is their smallest upper bound.

+5


source







All Articles