stackoverflowed
stackoverflowed

Reputation: 927

List of trait in Scala

I am a bit confused about Scala traits. What is the exact meaning of

val myList = List[MyTrait]

where MyTrait is a trait.

Does't that mean that myList can contain any instance of class (MyClass) that mixes-in MyTrait ? If so, isn't it a bit weird because MyClass is not a MyTrait (or is it ?).

Thanks for your help.

Upvotes: 1

Views: 1745

Answers (4)

Jörg W Mittag
Jörg W Mittag

Reputation: 369556

I think, the real question you are asking is just this:

If so, isn't it a bit weird because MyClass is not a MyTrait (or is it ?).

It is. MyClass inherits from MyTrait, so MyClass IS-A MyTrait.

Upvotes: 1

ulas
ulas

Reputation: 473

trait A
trait B

class C extends A with B

val aList = List[A]()
// aList: List[A] = List()

val bList = List[B]()
// bList: List[B] = List()

new C :: aList
// res1: List[A] = List(C@1124910c)

new C :: bList
// res2: List[B] = List(C@24d7657b)

Class C inherits both A and B traits. So it's not weird.

Upvotes: 1

Jasper-M
Jasper-M

Reputation: 15086

If you have

trait MySuperTrait
trait MyTrait extends MySuperTrait
trait MyOtherTrait
abstract class MyAbstractClass
class MyClass extends MyAbstractClass with MyTrait with MyOtherTrait

Then MyClass IS A:

  • MyAbstractClass
  • MyTrait
  • MySuperTrait
  • MyOtherTrait
  • AnyRef / java.lang.Object
  • Any

So you can use an instance of MyClass anywhere where one of those types (or MyClass itself) is required.

Upvotes: 1

meucaa
meucaa

Reputation: 1515

Indeed, if you declare your list as a List[MyTrait], it will be a container for any object that mixes-in MyTrait.

To go further you can even specify a class and a trait like this:

If Animal is a class and Fly a trait that define the fly() method.

List[Animal with Fly] will be a list of all the animals who can fly.

Upvotes: 1

Related Questions