How Scala Traits behave?

2019-04-18 01:40发布

问题:

I created this small Scala example for understand better traits.

trait Writer {
  def write(value: Int): Unit = {
    print("Writer")
  }
}

trait Hdd extends Writer {
  override def write(value: Int): Unit = {
    print("Hdd")
  }
}

trait File extends Writer {
  override def write(value: Int): Unit = {
    print("File")
  }
}

class TestClass extends App {
  (1)   val myWriter = new Writer with Hdd   // This line looks fine
  (2)   val myNewWriter = new Writer         // This line fail
}

In my understanding, it's not possible to instantiate a Trait, and for this reason the line (2) is failing.

But for some reason that I'm not able to understand, the line (1) looks fine.

How this can be possible?

回答1:

Yes,you are right that a trait can not be instantiated in Scala.A trait cannot be instantiated, only mixed in. you need a class for instantiation and when you use "new writer with Hdd",it creates an anonymous class hence your instantiatation looks fine and does not give any error.And you get error for 2nd line as it is just a trait hence can't be instantiated.



回答2:

Try:

val myWriter = new Writer {}

I guess it needs an implementation, even if that implementation is empty



标签: scala traits