开发者

Why can I assign null to a Unit value and why does it get converted to ()?

开发者 https://www.devze.com 2023-02-28 16:00 出处:网络
Consider this code: var unit: Unit = null unit: Unit = () a) Why am I allowed to assign null to a value class? (see §12.2.3)

Consider this code:

var unit: Unit = null
unit: Unit = ()

a) Why am I allowed to assign null to a value class? (see §12.2.3)

b) Why doe开发者_运维百科s the null get converted to ()?


From the scala specification section 6.26.1:

Value Discarding. If e has some value type and the expected type is Unit, e is converted to the expected type by embedding it in the term { e ; () }.

In other words, your code is equivalent to

var unit: Unit = {null; ()}
unit: Unit = ()

The null isn't converted -- it's merely ignored and replaced by (), the predefined Unit value.

0

精彩评论

暂无评论...
验证码 换一张
取 消