Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of Kotlin "by lazy" in Java?

I'm following this article https://proandroiddev.com/detecting-when-an-android-app-backgrounds-in-2018-4b5a94977d5c to implement android lifecycle but on a legacy app that has the Application class on java.

How can I implement this kotlin code in java?

private val lifecycleListener: SampleLifecycleListener by lazy {
    SampleLifecycleListener()
}

I feel that is a dumb question, but I'm not familiar with lazy initialization and I'm not sure how to search this question, any "lazy theory link" will be welcome also.

like image 790
rubdottocom Avatar asked Apr 19 '18 16:04

rubdottocom


3 Answers

You can call Kotlin lazy from Java if you want to:

import kotlin.Lazy;

Lazy<SampleLifecycleListener> lazyListener = kotlin.LazyKt.lazy(() -> new SampleLifecycleListener()));
SampleLifecycleListener realListener = lazyListener.getValue();
like image 149
David Rawson Avatar answered Nov 09 '22 07:11

David Rawson


private SampleLifecycleListener sll;

public synchronized SampleLifecycleListener getSampleLifecycleListener() {
    if (sll == null) {
        sll = new SampleLifecycleListener();
    }
    return sll;
}

That way it isn't initialized until the getter is called.

like image 42
Bakon Jarser Avatar answered Nov 09 '22 07:11

Bakon Jarser


Beginning with Java 8, you can use ConcurrentHashMap#computeIfAbsent() to achieve laziness. ConcurrentHashMap is thread-safe.

class Lazy {
    private final ConcurrentHashMap<String, SampleLifecycleListener> instance = new ConcurrentHashMap<>(1);

    public SampleLifecycleListener getSampleLifecycleListener() {
        return instance.computeIfAbsent("KEY", k -> new SampleLifecycleListener()); // use whatever constant key
    }
}

You can use this like

SampleLifecycleListener sll = lazy.getSampleLifecycleListener();
like image 37
naXa Avatar answered Nov 09 '22 07:11

naXa