user1484819
user1484819

Reputation: 919

Scala inheritance with a abstract class

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.

Upvotes: 1

Views: 1021

Answers (2)

dhg
dhg

Reputation: 52701

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())

Upvotes: 4

Kim Stebel
Kim Stebel

Reputation: 42045

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

class Input(codes: Array[Char]) extends Device(codes) {
  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]

Upvotes: 3

Related Questions