简体   繁体   中英

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.

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.

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();

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM