1

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.

meucaa
  • 1,455
  • 2
  • 13
  • 27
stackoverflowed
  • 686
  • 8
  • 22
  • http://stackoverflow.com/questions/663254/why-doesnt-the-example-compile-aka-how-does-co-contra-and-in-variance-w – vvg Jun 17 '16 at 09:58

4 Answers4

1

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.

meucaa
  • 1,455
  • 2
  • 13
  • 27
1

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.

Jasper-M
  • 14,966
  • 2
  • 26
  • 37
1
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.

ulas
  • 463
  • 5
  • 10
1

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.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653