HadoopDev007 HadoopDev007 - 5 days ago 5
Scala Question

Explicit getter in Scala

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

val myCar = new Car(100,2016);
println(myCar.miles)


This
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

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
}
Comments