MaatDeamon
MaatDeamon

Reputation: 9771

Compound type vs mixins in scala

readying about compound type in programming scala 2nd edition, and left with more question than answers.

When you declare an instance that combines several types, you get a compound type:

trait T1
trait T2
class C
val c = new C with T1 with T2  // c's type: C with T1 with T2

In this case, the type of c is C with T1 with T2. This is an alternative to declaring a type that extends C and mixes in T1 and T2. Note that c is considered a subtype of all three types:

val t1: T1 = c
val t2: T2 = c
val c2: C  = c

The question that comes to mind is , why the alternative ? If you add something to a language it is supposed to add some value, otherwise it is useless. Hence, what's the added value of compound type and how does it compare to mixins i.e. extend ... with ...

Upvotes: 2

Views: 302

Answers (1)

Dmytro Mitin
Dmytro Mitin

Reputation: 51683

Mixins and compound types are different notions:

https://docs.scala-lang.org/tour/mixin-class-composition.html

vs.

https://docs.scala-lang.org/tour/compound-types.html

Mixins are traits

trait T1
trait T2
class C
class D extends C with T1 with T2
val c = new D

Partial case of that is when an anonymous class is instead of D

trait T1
trait T2
class C
val c = new C with T1 with T2 // (*)

Compound types are types

type T = Int with String with A with B with C

Type of c in (*) is a compound type.

The notion of mixins is from the world of classes, inheritance, OOP etc. The notion of compound types is from the world of types, subtyping, type systems, type theory etc.


The authors of "Programming in Scala" mean that there is an alternative:

  • either to introduce D

    (then D extends two mixins, namely T1 and T2, type of c is D)

  • or not

    (to use anonymous class instead of D, type of c is a compound type).

Upvotes: 1

Related Questions