Difference between underscore initialization of var and val

后端 未结 2 942
执念已碎
执念已碎 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条回答
  •  闹比i
    闹比i (楼主)
    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]
    

提交回复
热议问题