“new” keyword in Scala

后端 未结 3 1382
遇见更好的自我
遇见更好的自我 2020-11-28 20:08

I have a very simple question - when should we apply the new keyword when creating objects in Scala? Is it when we try to instantiate Java objects only?

3条回答
  •  隐瞒了意图╮
    2020-11-28 20:24

    Is it when we try to instantiate java objects only?

    Not at all. There is two general cases when you ommit new in scala. With singleton objects (that are oftenly used to store static functions and as a kind of factory similar to what you may seen in java):

    scala> object LonelyGuy { def mood = "sad" }
    defined module LonelyGuy
    
    scala> LonelyGuy
    res0: LonelyGuy.type = LonelyGuy$@3449a8
    
    scala> LonelyGuy.mood
    res4: java.lang.String = sad
    

    With a case classes (actually, underneath there are class + object = companion pattern, e.g. having class and object with the same name):

    scala> case class Foo(bar: String) 
    defined class Foo
    
    
    scala> Foo("baz")
    res2: Foo = Foo(baz)
    

    So when you work with a simple classes, rules are the same as with Java.

    scala> class Foo(val bar: String) 
    defined class Foo
    
    scala> new Foo("baz")
    res0: Foo = Foo@2ad6a0
    
    // will be a error 
    scala> Foo("baz")
    :8: error: not found: value Foo
           Foo("baz")
    

    Bonus, there is a anonymous classes in scala, which can be constructed like this:

    scala> new { val bar = "baz" }
    res2: java.lang.Object{val bar: java.lang.String} = $anon$1@10ee5b8
    
    scala> res2.bar
    res3: java.lang.String = baz
    

提交回复
热议问题