Take the 2-minute tour ×

I am new to scala, just doing some practice; I tried a very simple program, briefed as following:

abstract class Device(val cds: Array[Char]) {
  var codes = Array[Char](cds: _*)
  def encrpt(code: Char): Char

  var nextDevice: Device

  def setNext(next: Device):Unit = {
    nextDevice = next

//compiler error shows here
class Input(codes: Array[Char]) extends Device(codes) {
  override def encrpt(code: Char) = code

you could see there is a compiler error at line 21, following is the message: class Input needs to be abstract, since variable nextDevice in class Device of type com.me.acm.problem1009.Device is not defined (Note that variables need to be initialized to be defined)

I am pretty confusing that error, my understanding, define some variable and an setter method in the parent class, so the child classes can use it without define it again. it is straight forward.

I guess I missed something. Could someone explain it to me and tell what is the correct way? thanks.

share|improve this question
Note you don't have to explicitly declare getter and setter, var declarations are expanded into getters and setters for you implicitly. See this for how this occurs for concrete members, and that for abstract members. –  huitseeker Jan 7 '13 at 12:48

2 Answers 2

up vote 4 down vote accepted

In Scala, variables do not have assumed default values as they do in Java (or many other languages). Thus, when you declare a variable, you must always specify its initial value.

In your code, you declare a variable nextDevice, but you do not give it a value. Since Scala always needs a value, it interprets what you've written as nextDevice being an abstract field, so the compiler is telling you that it must be overridden.

If you change that line to the following, for example, to specify an initial value, then the error will disappear:

var nextDevice: Device = new Input(Array())
share|improve this answer
thanks, it is pretty helpful. –  user1484819 Jan 7 '13 at 7:02

As the error message is telling you, the variable nextDevice needs to be initialized in the constructor on Input.

  override def encrpt(code: Char) = code
  nextDevice = null

Note that using null is frowned upon in Scala. You should probably change the type of your variable to Option[Device]

share|improve this answer
Thanks a lot, it is more clear now. –  user1484819 Jan 7 '13 at 7:03

Your Answer


