The reason that inheritance can limit the target composition of the target

I knew that inheriting from a based class could limit the class with which it can mix. This is a well-known method of adding constraints when mixing:

class Foo
trait FooTrait extends Foo
val pass = new Foo with FooTrait
class Bar
val error = new Bar with FooTrait //illegal inheritance: superclass Bar is not a subclass of the superclass Foo of the mixin trait FooTrait

or

abstract class Foo
trait FooTrait extends Foo
class Bar
val error = new Bar with FooTrait //illegal inheritance

Is this just special syntax for this purpose?

I ask this because I cannot figure out how to explain this using the concept of inheritance . Also, I cannot explain the opposite result if you inherit a trait instead of an abstract class:

trait Foo
trait FooTrait extends Foo
class Bar
val pass = new Bar with FooTrait // no restriction!  
+4
source share
1 answer

Key to understanding here are the following:

  • Scala traits , . .
  • , class trait.

trait , AnyRef.

, - :

class Foo                  \\ 1 
trait FooTrait extends Foo \\ 2
class Bar extends FooTrait \\ 3

.

val bar = new Bar with FooTrait

.

, Bar. . val bar = new Bar, Bar Bar. Bar.

, , - val bar = new Bar with FooTrait, . :

  • Bar,
  • Foo, Footrait

JVM , , . . :

trait Foo
trait FooTrait extends Foo
class Bar
val pass = new Bar with FooTrait // no restriction!  

, Java.

+4

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


All Articles