val and object inside a scala class?

前端 未结 7 2208
广开言路
广开言路 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:27

    One major difference is that val's can be overriden while objects can't.

    class C extends B {                           
      override val a1 = new A { def foo = 2 }     
      override object a2 extends A { def foo = 2 }
    }
    

    leads to:

    :9: error: overriding object a2 in class B of type object C.this.a2;
    object a2 cannot be used here - classes and objects cannot be overridden
    override object a2 extends A { def foo = 2 }
    

提交回复
热议问题