Scala tracks mixin and super call order

I have this code:

trait base{ def msg: Unit= { println{"base"} } } trait foo extends base { abstract override def msg: Unit ={ super.msg println("foo") } } class base2{ def msg:Unit = { println{"base 2"} } } class test extends base2 with foo{ override def msg: Unit ={ super.msg println("done") } } 

If I call (new test).msg , it prints things like: base, foo, done

However, if I changed the underlying attribute to:

 trait base{ def msg: Unit } 

it prints things like: base 2, foo, done

I understand that the with order is from right to left (last in first place), but what about extends ? Sometimes it happens that it prints base2 , but sometimes base ?

+6
source share
2 answers

When you omit the implementation, base is a trait template and has different pricing rules. See Scala specification

+1
source

Scala has something called type linearization. It defines the initialization order. Read here http://eed3si9n.com/constraining-class-linearization-in-Scala

+1
source

Source: https://habr.com/ru/post/979933/


All Articles