HadoopDev007 HadoopDev007 - 1 year ago 143
Scala Question

Explicit getter in Scala

class Car(val miles:Int,val year:Int)

val myCar = new Car(100,2016);

myCar .miles
gives me the value.But I want to define explicit getter do something with value of miles property of myCar.How to do this..

Answer Source

Define a method:

class Car(mi: Int, val year: Int) {
  def miles = 2 * mi

val myCar = new Car(100, 2016)
println(myCar.miles)   // prints 200

Or, since the value is immutable, define a val so that the computation is done only once (instead of every time you call the method):

class Car(mi: Int, val year: Int) {
  val miles = 2 * mi
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download