Val and def

class Cons[T](val head: T, val tail: Int)

In the above class definition ‘val’ means, that the class has the fields head and tail. Without ‘val’ those fields are private. So ‘val’ is a way to define a field in a class.

“They are special cases of methods, they can override methods and implement abstract methods and traits. The difference between a val and a def concerns only the initialization. A val is evaluated when the object is first initialized, whereas a def is evaluated each time it is referenced.” (Martin Odersky, coursera course “Functional Programming Principles in Scala”, Polymorphism.


Discover more from Master the Math

Subscribe to get the latest posts sent to your email.

Scroll to Top
Cookie Consent with Real Cookie Banner