Showing posts with label Kotlin. Show all posts
Showing posts with label Kotlin. Show all posts

Wednesday, 8 April 2026

VoxxedDays 2026

So, I went to VoxxedDays on April 1st and 2nd.1

Some of it was very interesting, and I've retained some notes and links written below.

Spec-driven development2
It seems to be a way to specify the wanted behaviour of your software in such a way that AI can successfully create your software based on your spec. Not entirely convinced of this.
Lion3
Lion is a set of highly performant, accessible and flexible Web Components.
PicNic4

PicNic is a online greengrocer/supermarket which is running a Blog on the challenges on scaling up. Quite interesting.

Some interesting things for example are providing fresh products (bread for instance) within a certain timeframe.

Programming Rules your IDE can tell you about.
https://github.com/jborgers/PMD-jPinpoint-rules
Compressed OOPs in the JVM
https://www.baeldung.com/jvm-compressed-oops
A good explanation of generics
https://bramjanssens.nl/generics/
Reduce Object Header Size and Save Memory in Java 25
https://www.baeldung.com/java-object-header-reduced-size-save-memory

The sessions are online now at YouTube. See [5].

References

[1] VoxxedDays Amsterdam
https://amsterdam.voxxeddays.com/
[2] What Is Spec-Driven Development? A Complete Guide
https://www.augmentcode.com/guides/what-is-spec-driven-development
[3] Github - Ing/Lion
https://github.com/ing-bank/lion
[4] PicNic - Blog
https://blog.picnic.nl/
[5] YouTube - VoxxedDays 2026 Sessions
https://youtube.com/playlist?list=PLRsbF2sD7JVoK114W2u9HTK4ftHn_taT1&si=WmiCtfuhEyTtu0lg

Monday, 16 March 2026

Kotlin: lots of functions

I like Kotlin (sometimes) as it has a large and rich number of convenient functions to use.

In Java, we tend to reach for our Guava1 or Apache Commons Lang2 to get the same functionality.

But it does tend to make it a bit hard to decide which to use, especially as I (as most people I hope) do not know the entire dictionary of available functions in Kotlin.

Luckily there's of course colleagues who can help, and my IDE also does a pretty good task of suggesting better ways.

Case in point:

val items : List<Items> = getItems()
val coupon: Coupon? = items.map { it.coupon }.filter { it != null }.firstOrNull()

I do know the code above can be made simpler.

val items : List<Items> = getItems()
val coupon: Coupon? = items.mapNotNull { it.coupon }.firstOrNull()

There, the mapNotNull() is a very convenient function that I use all the time.

But this time my IDE complained again and told me to use .firstNotNullOfOrNull

val items : List<Items> = getItems()
val coupon: Coupon? = items.firstNotNullOfOrNull { it.coupon }

It's fine by me, to use this, but I didn't know this function exists.

Also, the name seems a bit long and it took a minute to understand the meaning.

References

[1] GitHub - Google Guava
https://github.com/google/guava
[2] Maven Repository - Apache Commons Lang (3)
https://mvnrepository.com/artifact/org.apache.commons/commons-lang3

Thursday, 12 February 2026

AssertJ + AutoCloseableSoftAssertions + Kotlin

I've been playing around with AutoCloseableSoftAssertions, as I don't want to have to remind myself to call .assertAll()

But I also wanted to see if I can replace entire rows of assertThat statements in a simple manner, without many changes.

And I think I have found a way in Kotlin.

Let's start with the basics:

Let's try some SoftAssertions, so we can have many asserts that are all evaluated, instead of the Test stopping upon the first failed assert.

Okay, now AutoCloseableSoftAssertions is a convenient class that calls the .assertAll() as part of the final block in a try-with-resources:

Now, in the case above, we have to prefix our assertThat() calls with "it.". There's one more step that we can use to remove this.

Wrapping all this in a function for easy use will end up in:

Now, a stack of assertThat() statements can be encompassed with assertAll{} without any other changes to get the full advantages of SoftAssertions.

Might be overkill, but this was a fun example in Kotlin.

Try-with-resources

So you might have noticed that AutoClosableSoftAssertions is used in a try-with-resources block.

The small advantage you have, is that if there is an unexpected Exception thrown during your asserts, the ".assertAll()" will still be called, because it's part of the "AutoCloseable.close()".

I don't know how much this advantage is, as the unexpected Exception breaks the test anyways, but there it is.

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?

Friday, 28 November 2025

Kotlin: From List To Map

So I've been trying to make a Map from a List in Kotlin, and as I have not much experience with Kotlin and not much experience with Maps, I turn to the Internet.

Funnily enough, after getting it working, my IDE keeps giving me subtle hints that it can be shorter and more concise.

I thought it would be nice to put the steps here.

val primaryKeys = listOf(12L, 15L, 16L, 22L, 204L)
val firstTry = primaryKeys.map { it to getUser(it) }

In the example above it's not a Map yet, but it's a good first step.

As you can tell, it transforms your list into another List of type List<Pair<Long, User>>.

Kotlin has a toMap() method that does what we want.

    @Test
    fun testListToMapConversion() {
        val primaryKeys = listOf(12L, 15L, 16L, 22L, 204L)
        val map = primaryKeys.map { it to getUser(it) }.toMap()
        assertThat(map).isEqualTo(
            mapOf(
                12L to User(12L, "Bob"),
                15L to User(15L, "Jimmy"),
                16L to User(16L, "Jack"),
                22L to User(22L, "Henry"),
                204L to User(204L, "William")
            )
        )
    }

Now my IDE tells me this can be shortened.

    @Test
    fun testListToMapConversion() {
        val primaryKeys = listOf(12L, 15L, 16L, 22L, 204L)
        val map = primaryKeys.associate { it to getUser(it) }
        assertThat(map).isEqualTo(
            mapOf(
                12L to User(12L, "Bob"),
                15L to User(15L, "Jimmy"),
                16L to User(16L, "Jack"),
                22L to User(22L, "Henry"),
                204L to User(204L, "William")
            )
        )
    }

Now my IDE tells me this can be shortened AGAIN!

    @Test
    fun testListToMapConversion() {
        val primaryKeys = listOf(12L, 15L, 16L, 22L, 204L)
        val map = primaryKeys.associateWith { getUser(it) }
        assertThat(map).isEqualTo(
            mapOf(
                12L to User(12L, "Bob"),
                15L to User(15L, "Jimmy"),
                16L to User(16L, "Jack"),
                22L to User(22L, "Henry"),
                204L to User(204L, "William")
            )
        )
    }

Nice!

References

Syntax Highlighter
https://highlight.hohli.com/

Thursday, 20 November 2025

Kotlin: Redundant SAM constructor

Kotlin lambdas are fully compatible with Java functional interfaces.

But sometimes you need to give Kotlin a little nudge, using a SAM constructor.

SAM constructors (Single Abstract Method) allow you to convert a lambda expression to an instance of a functional interface. The syntax is pretty straightforward.

FunctionalInterfaceName { lambda_function }

The message in the title appears when you use a SAM constructor, when you don't have to. Kotlin is smart enough to create the appropriate anonymous class without us being specific in most cases.

I notice this happening sometimes when I have IntelliJ convert my Java class automatically to Kotlin.

A simple example:

// Java
public Builder addMapping(FieldMetadata field, Supplier<?> valueSupplier) {...}
// redundant Kotlin
val fieldMapping = FieldMapping.builder()
.addMapping(OrderItemField.ITEM_NR), Supplier { orderRepository.getOrderItem })
.build()
// correct Kotlin
val fieldMapping = FieldMapping.builder()
.addMapping(OrderItemField.ITEM_NR) { orderRepository.getOrderItem }
.build()

References

Medium - Idiomatic Kotlin: Lambdas and SAM constructors
https://medium.com/tompee/idiomatic-kotlin-lambdas-and-sam-constructors-fe2075965bfb

Thursday, 13 November 2025

Rename .java to .kt

So, I've suddenly recently noticed that whenever I commit a change into Git in IntelliJ that contains a conversion of a .java file into a .kt (Kotlin) file, IntelliJ will automatically make a previous commit containing the comment "Rename .java to .kt" which contains ONLY the renaming of the file.

I thought this was odd, but the reason behind it is that this commit helps Git to bind the two files together in the History.

If you do not have this single commit, (for example, if you're merging this to your integration branch or whatever and you squash your commits), you lose the history. It means Git will see the .java file as a file that has been deleted and the .kt file as a new file that has been added.

Some people complain, but it really depends on what is important to you:

  • do you want to preserve your history in Git for a file
  • or
  • do you want to see the changing the filename as belonging to your commit (and your ticketnumber in de comments)

Ideally, you should bear in mind IntelliJ does this, so you can at least edit the Commit Message of the renaming to include your ticketnr and original comment and such.

Settings

Can you turn this setting off? Yes, you can. There's a checkbox in the settings of the Git Commit dialog.

Unfortunately, this interesting setting only appears when you have indeed converted a Java file into a Kotlin file.

References

Kotlinlang - slack-chats
https://slack-chats.kotlinlang.org/t/465094/hi-i-ve-discovered-to-my-surprise-that-the-java-to-kotlin-co

Thursday, 23 October 2025

No "new" keyword in Kotlin

So I was wondering what my opinion is about that.

I don't like it a lot, as now it seems like calling a constructor looks similar to calling a method.

The only difference that's visible is that the constructor begins with a capital, and then only if you properly follow the coding style guidelines.

I noticed that where Java prefers clarity of purpose, Kotlin prefers brevity (and sacrifices clarity for this).

In Java the "new" keyword does a lot of heavy lifting, that is not part of the constructor. The constructor merely sets the internal structure of an object-to-be to appropriate values. The responsibility of actually making the object, registering it in de Heap, doing the pointer bits, is indicated by the new keyword.

What are your opinions?

References

Reddit - Is keyword new redundant?
https://www.reddit.com/r/java/comments/1n0m7cg/is_keyword_new_redundant/
Kotlin Documentation - Classes
https://kotlinlang.org/docs/classes.html

Friday, 27 June 2025

Brain fart

Sometimes, when I'm programming, I haven't got a good idea of how to do something. What I do have is a large collection of really bad ideas, that I use when I don't have a good idea.

Apparently, good ideas take time. And sometimes they only happen after trying out some really horrendous ideas.

So, I checked the follwing String expression in Kotlin in, and I got some code review comments on it.

"$description $additionalDescription"

The comment was: "put a trim() on the entire thing, as the additionalDescription, which is provided by the user, can be anything (like for example spaces or just empty)".

And I got stuck on that. I came up with something horrendous like the following:

"${(description + additionalDescription).trim()}"

Of course you can immediately see where I went wrong, but once you get invested in the String template solution, sometimes it's hard to break out of that solution again.

The solution I went for was (obviously):

"$description $additionalDescription".trim()

Thursday, 24 April 2025

Compatiblity between Kotlin and Java regarding Default Methods

In short, default methods in interfaces in Kotlin are not compatible with Java.

That's the short version.

The long version follows.

Let's have a simple Person interface written in Kotlin:

Now we wish to use it in Java.

This doesn't work. Although the interface defines a default implementation of getGender(), this default implementation is invisible when called from Java.

java: org.mrbear.kotlin.interfaces.MrBear is not abstract and does not override abstract method getGender() in org.mrbear.kotlin.interfaces.Person

Now, in the past there used to be something called @JvmDefault, but that is deprecated and doesn't work.

Instead it has been superseded by @JvmDefaultWithoutCompatibility1 and @JvmDefaultWithCompatibility2 (which, quite frankly, makes it a tad less understandable).

Also, when you use either annotation, you are required to add a command line parameter when you compile, or it won't work.

With compatibility requires -jvm-default=enable.

Without compatibility requires -jvm-default=no-compatibility.

However, it seems that the default is with compatibility that it is turned on automatically in Kotlin 2.2. Which will be released soonish hopefully.

How it works

Apparently what happens is that Kotlin automatically creates an Abstract class in the Interface that implements the methods that are default (under water). The abstract class is called Interface$DefaultImpls.

If you run Without Compatibility, it means that the DefaultImpls won't be generated but only "real Java default methods in the Interface". This means your interface in Kotlin will actually change (and is therefore not backwards compatible).

See reference [3] for more details.

References

[1] Kotlin LangRef - JvmDefaultWithoutCompatibility
https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.jvm/-jvm-default-without-compatibility/
[2] Kotlin LangRef - JvmDefaultWithCompatibility
https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.jvm/-jvm-default-with-compatibility/
[3] KT-4779 Generate default methods for implementations in interfaces
https://youtrack.jetbrains.com/issue/KT-4779/Generate-default-methods-for-implementations-in-interfaces

Tuesday, 4 March 2025

Kotlin Operator Overloading

So my colleague mentioned operator overloading, and how much fun it is.

So I wrote a little test.

It works pretty good, but for infix functions it has a very high "syntactic sugar" and less about "real" operator overloading.

Also, the reference page in [1] indicates that for Infix functions, the precedence has fixed rules that do not (always) conform to precedence that we would assume.

My colleague told me that a number of infix functions were created for QueryDSL, so we could write a semblance of SQL in Kotlin, but the precedence tends to screw things up.

We removed these infix functions from our source code again.

So, use sparingly and only when it makes sense. For example if it makes your code a magnitude easier to read/reason about and preferable with as small a scope as possible.

References

[1] KotlinLang - Functions
https://kotlinlang.org/docs/functions.html#function-scope
Baeldung - Operator Overloading in Kotlin
https://www.baeldung.com/kotlin/operator-overloading
Baeldung - Infix Functions in Kotlin
https://www.baeldung.com/kotlin/infix-functions

Thursday, 19 December 2024

Kotlin and Java and Interfaces and Automatic Getters and Setters

Kotlin is great, Java is great, but there are sometimes little things that can be a little bit tricky. Especially when combining the two.

I am going to talk about one tricky thing now.

So we have an interface in Java:

And I wish to implement it using an enum in Kotlin.

Like so:

Obviously this will break, because a public val description automatically gets a getter in Kotlin, which conflicts with the implementation of the getDescription method.

You'll get error messages during compile time like this:

Platform declaration clash: The following declarations have the same JVM signature (getDescription()Ljava/lang/String;):
Platform declaration clash: The following declarations have the same JVM signature (getDescription()Ljava/lang/String;):

Well, you think, that's fine. If Kotlin already makes a getDescription automatically, I can simply remove my method getDescription() from the enum.

But that doesn't work. It immediately starts complaining that you have not implemented all members of the interface.

The way to solve it is to make the description field private ("private val description: String") so Kotlin no longer automatically creates a getter.

Trivial but a bit surprising.

From what I can tell, Kotlin is being careful not to create what they call "accidental overrides".

References

YouTrack - KT-6653 - Kotlin properties do not override Java-style getters and setters (created 10 years ago)
https://youtrack.jetbrains.com/issue/KT-6653
YouTrack - KT-19444 - Add JVM-specific annotation to permit "accidental" overrides of interface members
https://youtrack.jetbrains.com/issue/KT-19444

Thursday, 28 November 2024

Solution: Problems with Kotlin

Well, the solution to [1] is obviously that you are missing a "&&".

This causes Kotlin to assume the expression:

it.address.country == "United Kingdom"

... is the expression that needs to be returned. This causes the code to spit out all people currently in the United Kingdom.

It took me a little while to notice the problem. My IDE didn't help in the slightest.

References

[1] Problems with Kotlin
https://randomthoughtsonjavaprogramming.blogspot.com/2024/11/problems-with-kotlin.html

Tuesday, 26 November 2024

Problems with Kotlin

So, I was working and it didn't work.

And I really could not understand why.

Here's the code:

    @Test
    fun test() {
        val addressInNetherlands =
            Address(housenumber = 11L, street = "Kerkstraat", city = "Amsterdam", state = null, country = "Netherlands")
        val addressInEngland = Address(12, "Morsestreet", "London", null, "United Kingdom")
        val anotherAddressInEngland = Address(28, "Trinity Ln", "Cambridge", null, "United Kingdom")
        val addressInAmerica = Address(23, "32nd Street", "Columbus", "Ohio", "United States of America")

        val mrBear = Person("Mr.", "Bear", 50, addressInNetherlands)
        val mrBell = Person("Bell", "Graham", 55, addressInAmerica);
        val mrBoole = Person("George", "Boole", 82, addressInEngland);
        val lordKelvin = Person("William","Kelvin",84, anotherAddressInEngland);

        val addressBook = listOf(mrBear, mrBell, mrBoole, lordKelvin)

        var findMrBooleInEngland = addressBook.filter {
            it.firstName == "George" &&
                    it.lastName == "Boole"
                    it.address.country == "United Kingdom"
        }

        assertThat(findMrBooleInEngland).hasSize(1)
    }

Why does the assert fail? (it's programmer error, but almost invisible)

Solution in the next blog post.

Friday, 12 July 2024

Kotlin: The Spead Operator

Recently ran into a brick wall trying to pass a varargs parameter to another function that also has a varargs parameter.

A colleague mentioned the "spread" operator to me and it took me a little while to find information about it.

An example

package org.mrbear.kotlin

enum class ErrorCode(val description: String) {
    OBJECT_NOT_FOUND("Object %s not found."), NO_DEFAULT_PROVIDED("No default provided for parameter %s."), MALFORMED_URL(
        "Malformed url (%s)"
    )
}

abstract class MyException : Exception {
    constructor(errorCode: ErrorCode, cause: Throwable, vararg params: Any) : super(
        String.format(
            errorCode.description,
            *params
        ), cause
    )

    constructor(errorCode: ErrorCode, vararg params: Any) : super(String.format(errorCode.description, *params))
}

class ObjectNotFoundException(vararg params: Any) : MyException(ErrorCode.OBJECT_NOT_FOUND, *params)

Now to throw it in a test.

class ExceptionTest {

    @Test(expectedExceptions = [ObjectNotFoundException::class], expectedExceptionsMessageRegExp = "Object User mrbear not found.")
    fun testException() {
        throw ObjectNotFoundException("User mrbear")
    }
}

References

Kotlin - Variable number of arguments (varargs)
https://kotlinlang.org/docs/functions.html#variable-number-of-arguments-varargs
Kotlin - Java varargs
https://kotlinlang.org/docs/java-interop.html#java-varargs
Baeldung - Convert Kotlin Array to Varargs
https://www.baeldung.com/kotlin/array-to-varargs
Baeldung - Varargs in Java
https://www.baeldung.com/java-varargs

Monday, 3 June 2024

Kotlin Scope Functions

Scope function examples below:

  • let
  • with
  • run
  • apply
  • also
  • takeIf and takeUnless
  • Using them all at the same time!!!

I really hope I'm not the only one that gets confused about the different Scope functions1 in Kotlin and what they mean and when to use what.

The reference in [1] is excellent, but if I have to look up documentation on what certain methods do, the methods are not very well named.

So, in short, here's some examples, actually gleaned from the documentation and given my own spin on it with things that actually make sense.

Let

    /**
     * Useful if you do not wish to assign the result to an intermediate variable.
     * Useful with ? in case the result is NULL.
     */
    fun getDescription(address: Address?): String? =
        address?.let { address.getDescription() }

With

    /**
     * "with this object, do the following."
     * We're not interested in the result.
     */
    @Test
    fun withTest() {
        with(addressInEngland) {
            assertThat(street).isEqualTo("Morsestreet")
            assertThat(city).isEqualTo("London")
        }
    }

    /**
     * "with a helper object, do the following."
     */
    @Test
    fun withHelperTest() {
        val description = with(addressHelper) {
            computeAddress(addressInEngland)
        }
        assertThat(description).isEqualTo("12 Morsestreet London")
    }

Run

    /**
     * "run the code block with the object and compute the result."
     * Nice if you need to use it in an expression.
     */
    @Test
    fun runAsExtentionFunctionTest() {
        val didItWork: Boolean = database.run {
            val address = retrieveAddressFromDatabase()
            addressInAmerica.pobox = "43000"
            updateInDatabase(addressInAmerica)
        }
    }

    /**
     * "run the code block and compute the result."
     * Does not have a "this" or "it". Nice if you need to use it in an expression.
     */
    @Test
    fun runAsNonExtentionFunctionTest() {
        val didItWork = run {
            val address = database.retrieveAddressFromDatabase()
            with(shippingService) {
                sendItemToAddress(address)
            }
            log("Item sent")
            success
        }
    }

Apply

    /**
     * "apply the following assignments to the object."
     * The most common use case is object configuration, as below.
     */
    @Test
    fun applyTest() {
        val sameObject = Address().apply {
            housenumber = 12L
            street = "Morsestreet"
            city = "London"
        }
    }

Also

/**
     * "and also do the following with the object."
     * A common use case is to also assign the object to a property/variable.
     */
    private fun createHomeAddress() =
        Address().apply {
            housenumber = 12L
            street = "Morsestreet"
            city = "London"
        }
            .also { homeAddress = it }

TakeIf and TakeUnless

    /**
     * "return/use the value if this condition is true"
     * The opposite is takeUnless.
     */
    @Test
    fun takeIfTest() {
        assertThat(addressInEngland.takeIf { it.state != null }).isNull()
        assertThat(addressInAmerica.takeIf { it.state != null }).isEqualTo(addressInAmerica)
    }

And now for the big one!!!

    /**
     * Let's try all of them at the same time!
     */
    @Test
    fun allScopesTest() {
        val mailingSentForNewAddress = Address()
            .apply {
                housenumber = 12L
                street = "N. High Street"
                city = "Columbus"
                state = "Ohio"
                country = "United States of America"
            }
            .also {
                homeAddress = it
                with(database) {
                    updateInDatabase(it)
                }
            }
            .takeUnless { mailingAlreadySent(it) }
            ?.run {
                sendMailing()
                log("Mailing sent to ${getDescription()}.")
                success
            } ?: false

        val mailingSentForAddress =
            with(addressInEngland) {
                takeUnless { mailingAlreadySent(this) }
                    ?.run {
                        sendMailing()
                        log("Mailing sent to ${getDescription()}.")
                        success
                    } ?: false
            }
    }

Here I have tried to make use of the Scope functions in such a way that the different operations make sense.

P.S. I take offence on using "it" as the automatic name for the argument of the lambda. It sounds too much like the old Java "int i" in for loops. In other words, "it" has no meaning and the meaning depends entirely on context.

There's too much "it" and too much "this" and the context switching when using several Scope functions makes my head hurt.

References

[1] Kotlinlang.org - Scope Functions
https://kotlinlang.org/docs/scope-functions.html#functions

Friday, 14 April 2023

KotlinConf 2023

So I was able to attend my first KotlinConf1.

My experience with Kotlin is fairly new. I enjoy programming in both Java and Kotlin. I decide on a case by case basis what I pick.

Our current code base is a mixed bag of the two.

Sessions

I attended the following sessions on April 13 2023:

Opening Keynote2
I got some interesting news on the Kotlin version 2.0. It's coming.
Kotlin & Functional Programming: pick the best, skip the rest (Urs Peter)
Finally a nice talk about functional programming, a clear explanation of the illusive Monad, and what the advantages are of functional programming and which way we're going. Also took a look at Arrow3 for more idioms with functions.
Dissecting Kotlin: Unsealing the Sealed, the SAM, and Other Syntax (Huyen Tue Dao)
What is idiomatic Kotlin? It gave a great overview of the different features there are already in Kotlin, and how they should be used, and what little things we need to pay attention to when we do use them.
Replacing SQL with Kotlin's 'dataframe' on the Las Vegas Strip (Andrew Goldberg)
A nice talk which explains well what a dataframe is. And that with dataframes you can basically do all the operations that I am used to performing on (relational) databases with SQL, but a lot faster, as you're doing things locally? Coupling different data sources together.
Confetti: building a Kotlin Multiplatform conference app in 40min (John O'Reilly, Martin Bonnin)
A good example of using GraphQL and Compose to multiplatform create different mobile apps. Interestingly, they decided not to use Compose for the IPhone, as using Compose apparently causes different UI behaviour (Android behaviour) on the IPhone. Also extremely interesting use of livetemplates.
The Changing Grain of Kotlin (Nat Pryce, Duncan McGregor)
An interesting talk by some folks who wrote a book ("Java to Kotlin: A Refactoring Guidebook"). The talk was about how Kotlin has evolved and how this impacts old code, how it shapes new code, and how it all interacts.

Sessions I would like to have seen if I had the time:

Writing backend APIs in a functional programming style (James Lamine)
Transforming Farmer's Lives Using Android in Kenya (Harun Wangereka)

I attended the following sessions on April 14 2023:

Six Impossible Things (Kevlin Henney)
Massively entertaining talk about software design in general, and some of its history.
Coroutines and Loom behind the scenes (Roman Elizarov)
Very informative talk, basically centering on what the reason was for creating Loom and what the reason was for creating Coroutines and why they can co-exist.
KotlinX Libraries (Anton Arhipov, Svetlana Isakova)
Very informative talk, basically the extended libraries you can use to make your application independent of platform. Serialization, Coroutines, Immutable collections, and more.
How we’re improving performance of IntelliJ IDEA Kotlin plugin (Vladimir Dolzhenko)
Very interesting, contains some tidbit on why some of the things in the plugin are so difficult, as well as how much Kotlin leans on the Java AST and the compiler.
Kotlin Native for CLIs (Ryan Harter)
An explanation on what things to use and what problems you encounter and some benchmarks on creating native commandline tools using Kotlin. In this case it was "differ" a fairly simple tool for compare two images.
Gilded Rose Refactoring Kata (Dmitry Kandalov)
A refactoring kata primarily done with the standard refactoring possibilities for Kotlin in the IntelliJ IDEA. The Kata is from github5 created by Emily Bache6.

Sessions I would like to have seen if I had the time:

Handling billions of events per day with Kotlin Coroutines (Florentin Simion, Rares Vlasceanu)
Evolving your Kotlin API painlessly for clients

I think all sessions will be viewable sometime on the youtubes.

References

[1] KotlinConf 2023
https://kotlinconf.com/
[2] KotlinConf 2023 - Keynote
https://www.youtube.com/watch?v=c4f4SCEYA5Q
[3] Arrow brings idiomatic functional programming to Kotlin
https://arrow-kt.io/
[4] http4k - The Functional toolkit for Kotlin HTTP applications
https://www.http4k.org/
[5] github.com - Gilded Rose Refactoring Kata by Emily Bache
https://github.com/emilybache/GildedRose-Refactoring-Kata
[6] Emily Bache
https://github.com/emilybache

Thursday, 8 December 2022

Null handling in Kotlin

Just some notes, as I find myself forgetting the Null-safety features of Kotlin.

Actually, most of the text in this blog is basically already written in [1], so you might want to check there as well.

So, there are three possibiltiies:

// always has a value:
val name: String = "Mrbear"

// sometimes has a value:
val sometimesName: String? = null

// function in java, so no clue what it might be:
val date = LocalDate.now()
// the return value shows up in IntelliJ hints as LocalDate!

You can use if statements, of course, to check for nulls.

Sometimes this doesn't work, because it might be mutable, see [2].

Safe calls can be used, like so for example when person might be null:

val person: Person? = getPerson()
val name: String? = person?.name

Using let:

person?.name?.let{ println(it) }

Default values:

person?.name?:"Mrbear"

Throwing an exception if it's not there:

person?.name?:return null
person?.name?:throw NullPointerException("name is not there")

And then there's !!, for those who know what they're doing:

val now: LocalDate = LocalDate.now()!!

Safe casts if the cast is unsuccesfull:

val aInt: Int? = a as? Int

References

[1] Kotlin - Null safety
https://kotlinlang.org/docs/null-safety.html
[2] Smart cast to 'Type' is impossible, because 'x' is a mutable property that could have been changed by this time
http://randomthoughtsonjavaprogramming.blogspot.com/2022/09/smart-cast-to-type-is-impossible.html

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

Monday, 9 May 2022

Hibernate Entities in Kotlin

Did a little research what kind of Kotlin classes I should use when creating Entities for the Hibernate framework.

Data classes

Just a short blurp on the requirements that data classes need from [1]:

  • the primary constructor needs to have at least one parameter
  • all primary constructor parameters need to be marked as either val or var
  • data classes cannot be abstract, open, sealed or inner

Hibernate Entities

Just a short blurp on the JPA requirements of entities from [2]

  • The entity class must have a public or protected no-argument constructor.
  • The entity class must be a top-level class.
  • The entity class must not be final. No methods or persistent instance variables of the entity class may be final.
  • The persistent state of an entity is represented by instance variables, which may correspond to JavaBean-style properties. An instance variable must be directly accessed only from within the methods of the entity by the entity instance itself. The state of the entity is available to clients only through the entity’s accessor methods (getter/setter methods) or other business methods.

Conclusion

  • we need to define constructor parameters with var - as they should be mutable
  • we need to specify defaults for every constructor parameter, in order to generate the no-argument constructor
  • Hibernate entities should be "open" in Kotlin (so not final) in order for Hibernate to generate proxies. (this is fixed with the allopen addon in Maven)

So data classes are not a good fit, but a "normal" Kotlin class with just a constructor with annotated vars parameters with default values will work just fine.

References

[1] Kotlin - Data Classes
https://kotlinlang.org/docs/data-classes.html
[2] Hiberante ORM 5.5.9. Final User Guide
https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#entity
Medium.com - Defining JPA/Hibernate Entities in Kotlin
https://medium.com/swlh/defining-jpa-hibernate-entities-in-kotlin-1ff8ee470805