val and object inside a scala class?

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

    I suppose one difference is that a1 will be of one subtype of A while a2 will be of another subtype of A namely a2.type.

    scala> class A
    defined class A
    
    scala> val a1 = new A {def foo = 1}
    a1: A{def foo: Int} = $anon$1@a9db0e2
    
    scala> object a2 extends A {def foo = 1}
    defined module a2
    
    scala> a1
    res0: A{def foo: Int} = $anon$1@a9db0e2
    
    scala> a2
    res1: a2.type = a2$@5b25d568
    
    scala> 
    

提交回复
热议问题