Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance and traits

I found this reading another question:

"[...] a trait that extends a class puts a restriction on what classes can extend that trait - namely, all classes that mix-in that trait must extend that class"

a little example:

class C 
trait U
trait T extends C 

class D extends U with T // does not work
class E extends T with U // works

Apparently when traits inherit from classes, you have to put the trait in the position that you would otherwise place a class in (i.e. directly after extends)

Now to my questions:

(extended the previous example)

class C 
class Test
trait U
trait T extends C 
trait Tst extends Test


class D extends U with T // does not work
class E extends T with U // works
class Test2 extends Tst with T
  • what do we do when we want to inherit form two different traits, where each of those two inherit from a different class? (see class Test 2) this doesn't seem to be possible
  • if we need to pay attention to the placement of traits that extend a class, how do traits work then? Are traits inheriting from classes not "normal" traits anymore?
like image 499
user6454491 Avatar asked Dec 14 '25 15:12

user6454491


1 Answers

  1. This is indeed impossible. You cannot inherit from two different classes at once, whether via traits or otherwise. This is unfortunate, but true. There is no very good reason for that AFAICT, it would be somewhat harder to implement, but not impossible, at least for scala (not "native java") classes. So apparently, it was just decided against at some point, seemingly without a good reason.

  2. Traits that extend classes aren't really "abnormal". It's more like the way scala compiler handles them is. Basically, anything, that is or extends a class has to appear in the extends clause, and not in with. Why? Well, why can you not compare Strings in java with ==? because ...

like image 86
Dima Avatar answered Dec 18 '25 23:12

Dima