Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java modifies kotlin class content to null

Kotlin has a brilliant null checks at compile time using separation to "nullable?" and "notnullable" objects. It has a KAnnotator to help determine that objects coming from Java are nullabale or not. But what if some part of not-nullable class is changed?

Consider we have a cat, which certainly has a head that can meeew. When we ask the cat to mew, it mews with its head:

package org.cat

class CatHead(){
    fun mew(){
        println("Mew")
    }
}

class Cat(){
    var head = CatHead()
    fun mew(){
         head.mew()
    }
}

fun main(args:Array<String>){
   val cat = Cat()
   cat.mew()
}

Now lets add to this pretty picture a JAVA cat maniac (CatManiac.java), who cuts off a cats' heads as he gets:

import org.cat.*;

public class CatManiac {
    public static void cutCatHead(Cat cat){
         cat.setHead(null);
    }
}

So if we pass a cat to a maniac, he definitely cuts its head. And how cat says mew without a head?

fun main(args:Array<String>){
   val cat = Cat()
   CatManiac.cutCatHead(cat)
   cat.mew()
}

We get a runtime error inside kotlin because of null, at point of calling cat.mew():

Exception in thread "main" java.lang.IllegalArgumentException". 

I believe it is a pretty common problem we can get while using Java libraries in Kotlin. Is there any way or any plans to warn/fight with that?

P.S. Something like KAnnotator looking for such things in your code?

like image 790
MajesticRa Avatar asked Sep 07 '25 18:09

MajesticRa


1 Answers

There are checkers for Java code that will be extended for Kotlin code eventually.

For example, the one in IntelliJ will warn you about the problem right now. It's a part of the open-source Community Edition, so you can try it for yourself.

Meanwhile note that Kotlin gives you a great advantage over Java: it fail right at the point where the error is introduced. It's hard to pass a null through many Kotlin calls and only then get a failure. In Kotlin you mostly get a run-time error right where the illegal null is first introduced.

like image 157
Andrey Breslav Avatar answered Sep 10 '25 20:09

Andrey Breslav