Why does Scala language require you initialize a instance variable instead of relying on a default value?

前端 未结 3 733
有刺的猬
有刺的猬 2021-02-02 10:24

Scala language requires you initialize your instance variable before using it. However, Scala does not provide a default value for your variable. Instead, you have to set up its

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-02 10:43

    Scala has no issue with "var name: String" in the class body. Did you try it? It doesn't mean what you want it to mean, though. It's an abstract var.

    abstract class A {
      var name: String
    }
    // some possible uses for abstract vars
    trait B { type T ; var name: T }
    class B1 extends B { type T = Int ; var name: Int = 5 }
    // hey, no storage
    class B2 extends B { type T = String ; def name = "abc" ; def name_=(x: String) = () }
    

提交回复
热议问题