Difference between underscore initialization of var and val

后端 未结 2 815
执念已碎
执念已碎 2021-02-06 00:59

Why does val x: Int = _ not compile but var x: Int = _ does?

I\'m getting error: unbound placeholder parameter.

相关标签:
2条回答
  • 2021-02-06 01:28

    You can't reassign a vals value, so you cannot use _ (init with a default value for prescribed type) with it. But you can reassign a vars value, so it's a logical to initialize it with some default value, like in Java

    0 讨论(0)
  • 2021-02-06 01:55

    In this context, _ means "I will initialize this later, just fill in whatever the sensible default is in the meantime". Since you can't reassign a val, this doesn't make sense.

    For the same functionality--to get the sensible default--for a val, you can use

    val x: Int = null.asInstanceOf[Int]
    
    0 讨论(0)
提交回复
热议问题