Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ()?

like image 362
soc Avatar asked Apr 24 '11 16:04

soc


1 Answers

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.

like image 144
Ken Bloom Avatar answered Nov 09 '22 19:11

Ken Bloom