What is the difference between declaring a field as val
, lazy val
and object
inside a scala class, as in the following snippet:
This is not a structural type: val a = new A { def foo = 1 }
It creates a unique anonymous subclass; a.foo invokes foo in that class.
x here is a structural type: def bar( x: { def bass: Int} )
x.bass will introspect x (of unknown type) to find a method with name 'bass'. It will work with fish or musical instruments. ;)
One difference between the lazy val and object is this:
var someA = (new B).a3
someA = (new B).a3 // ok
var anotherA = (new B).a2
anotherA = = (new B).a2 // compile error