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

2
  • possible duplicate of Scala: Why can I convert Int to Unit? Commented Apr 24, 2011 at 17:10
  • Where do you see that () gets converted to null? Commented Apr 24, 2011 at 17:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.