Topic | Defining Properties/Fields in Scala Class/Object |
---|---|
Git sample(s) | VarAndValTest.scala & LazyValTest.scala |
- To declare a variable, use
var
/* Without type */
var variable = 0
/* With type */
var variableWithType: Int = 10
- To declare a constant, use
val
/* Without type */
val value= 8 * 5 + 2
/* With type */
val valueWithType: Int = 10 * 5 + 2
All
val
type variables are initialized before utilization. A Scalaval
is apublic static final
in JavaIf you want to defer this process of initiailization untill actuall utlization, use
lazy val
/* Lazy value without type */
lazy val lazyValue = 100
/* Lazy value with type */
lazy val lazyValueWithType: Int = 100
See how lazy values are handled in byte code
Scala provides keyword
def
for creating methods or definitions
def incrementDef = (x: Int) => x + 1 /* A definition using 'def' */