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

1

9

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 does the null get converted to ()?

Kore answered 24/4, 2011 at 16:53 Comment(2)
possible duplicate of Scala: Why can I convert Int to Unit?Boots
Where do you see that () gets converted to null?Boots
B
19

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.

Boots answered 24/4, 2011 at 17:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.