Showing posts with label nullsafety. Show all posts
Showing posts with label nullsafety. Show all posts

Thursday, 15 January 2026

Kotlin : NullSafety + Defaults

So, I had a discussion with my colleague about null safety and how it can be non-intuitive if you're not yet used to it.

So we had the following code:

In a lot of REST applications, an Exception may be thrown when a resource does not exist. But it's important to differentiate between "no resource" and "oh no! An exception occurred! We're in trouble!".

That's what this example code does.

So, what did the "getStatus" method do exactly?

This causes the test to fail.

The code should have been "?: false", but doing that does look weird.

A clearer solution would be:

The problem with Kotlin might be that there's alot of "?." and "?:" and "!!" and quite frankly it makes it hard to read.

What do you think?

Wednesday, 7 September 2022

Smart cast to 'Type' is impossible, because 'x' is a mutable property that could have been changed by this time

So I run into this problem quite often lately, most of the time it happens when I have defined a Hibernate Entity in Kotlin, and I wish to use it in my code.

It happens when there's a property that could conceivably be accessed in another thread, cause the two statements, the if-statement and the execution statement to look at different states, and cause a ClassCastException.

The following code demonstrates the message Kotlin provides when writing such a program:

Possible solutions

References

Youtube - Let, Also, Apply, Run, With - Kotlin Scope Functions
https://www.youtube.com/watch?v=Vy-dS2SVoHk