r/java • • Nov 04 '25

Anyone here Hated Using Java but now Really Enjoys using it.

title

226 Upvotes

280 comments sorted by

View all comments

Show parent comments

1

u/javaprof Nov 05 '25

- lazy can result in null even for not-nullable references

What do you mean here? Can you share some examples? I even have small DI on top of lazy (see komok-to-be-injected https://github.com/Heapy/di-comparison) and never hear about Kotlin's lazy doing that, it's just DCL under the hood

0

u/[deleted] Nov 05 '25

[removed] — view removed comment

1

u/javaprof Nov 06 '25

This is not even Kotlin's issues, this is Java Inheritance issue, you can found similar one when doing static initialization (it's also possible to deadlock during class initialization in java). Nothing to do with lazy:

open class Base {
    init {
        println("Base init: accessing derived.lazyValue = ${ (this as Derived).anyValue }")
    }
}
class Derived : Base() {
    val anyValue = "Definitely non-null"
}
fun main() {
    Derived()
}

So yes, Kotlin inherit some Java's issues, not everything is possible to solve and make language interoperable in both ways (keeping inheritance in language).

public final class TestKt {
    public static void main(String[] args) {
        new Derived();
    }
}

class Parent {
    public Parent() {
        System.out.println("Base init: accessing derived.lazyValue = " + ((Derived)this).getAnyValue());
    }
}

final class Derived extends Parent {
    @NotNull
    private String anyValue = "Definitely non-null";

    @NotNull
    public final String getAnyValue() {
        return this.anyValue;
    }
}

1

u/[deleted] Nov 06 '25

[removed] — view removed comment

1

u/javaprof Nov 06 '25

Bro, stop, lazy is not magic, it's just DCL, if it's called it called. Otherwise you're messing with class initialization and as I say, this is problem inherited from design of Java, as well as static initialization leads to nulls and deadlock, you can replicated them in Kotlin on JVM, not sure about other platforms tho.

Kotlin as type-system can't possibly catch that, and making everything nullable is not an option

1

u/javaprof Nov 06 '25

If you wish, it's just like StableValue/LazyConst from Java 25/26, but with much nicer access syntax in Kotlin:

https://www.reddit.com/r/Kotlin/comments/1n6z4e8/stable_values_as_replacement_for_lazy_delegate_on/