Sunday, 1 March 2015

Scala Puzzler 1: Overrides in Constructors

Question:


What is printed when the following code is executed?


Answer:


This code will print out 'null'.

This is because  the Person constructor is called before the override, meaning that val name is instantiated before the override is called. The default name value is never set because the compiler is clever enough to know we don't wan stringName to be set to "I dont have a name" so it skips that assignment.


Interestingly... 


If the stringName was declared with the 'lazy keyword' the code would work properly and print 'Alexandra'. This is because a lazy variable is declared as soon as it is needed, which in this case would be when the name class is instantiated.



No comments:

Post a Comment

Scala with Cats: Answers to revision questions

I'm studying the 'Scala with Cats' book. I want the information to stick so I am applying a technique from 'Ultralearning&#...