Prefer Kotlin’s val-iables instead of var-iables

Bill Tsapalos
3 min readApr 6, 2023

--

By using immutable content it is always easier to debug, do your thread handling and with no more details, you always know what is inside.

Can you guess the output for “??” lines?

The answer

You probably are here to make sure that your thought about the previous code snippet in the image is correct.

If you correct just let me know at the comments area!

So, what could be the result? Let me share my first thoughts! The me value is a Person with the name Bill. So far so good! Then we are changing the name of me to Vasilios. It seems that the people contains a Person with the name Vasilios. So we expect the following behavior:

  • me in people: Should print true
  • anotherMe in people: Should print false
  • me == anotherMe: Should print false
  • me == people.first(): Should print true

If this was your thoughts you are correct for 3 out of 4! Although me == people.first() is true, me in people is false! So, me is the first item in the list but me is not the list!

So, David Copperfield looks like a kid in front of me! Who is the one now?

The explanation

Let’s start with the actual code

If you are going to run this code using a debugger you are going to see that people is a LinkedHashSet

… which inherits from HashSet.

Let’s dive a little deeper and see what is going on inside the HashSet and the contains method because the people.contains(me) is equal to me in people.

Does HashSet contains a HashMap map? Now I start to have trust issues!

Let’s create a function to help us access the private members of a class through reflection, because we still need to investigate a little further.

The code we are working on at the moment is like this:

If we go back to the debugger once again we are going to see that the theMap is actually a LinkedHashMap.

If you are going to continue the investigation with the debugger you are going to see that the key of the node of the map (so weird syntax!) is something like out of sync. Beware of the way you use to print the hashcodes of the elements.

The solution

If you are going to use your data classes you truly need the hashCode() and equals() functionality (yes, they are going together. ALWAYS) make sure you use vals instead of vars. This way your data classes are much closer to the functionality of String which behaves like a primitive value! The proper way to have this example is the following:

More

Do you want to see more refactoring/design ideas? Here is the table of contents.

--

--