val and object inside a scala class?

前端 未结 7 2171
广开言路
广开言路 2020-11-29 03:59

What is the difference between declaring a field as val, lazy val and object inside a scala class, as in the following snippet:

<
7条回答
  •  有刺的猬
    2020-11-29 04:36

    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
    

提交回复
热议问题