簡體   English   中英

Java 中 Kotlin 的“懶惰”相當於什么?

[英]What is the equivalent of Kotlin “by lazy” in Java?

我正在關注這篇文章https://proandroiddev.com/detecting-when-an-android-app-backgrounds-in-2018-4b5a94977d5c來實現 android 生命周期,但在 Java 上具有 Application 類的遺留應用程序上。

我如何在 Java 中實現這個 kotlin 代碼?

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

我覺得這是一個愚蠢的問題,但我不熟悉惰性初始化,我不知道如何搜索這個問題,任何“惰性理論鏈接”也將受到歡迎。

private SampleLifecycleListener sll;

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

這樣它在調用 getter 之前不會被初始化。

從 Java 8 開始,您可以使用ConcurrentHashMap#computeIfAbsent()來實現惰性。 ConcurrentHashMap是線程安全的。

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
    }
}

你可以像這樣使用

SampleLifecycleListener sll = lazy.getSampleLifecycleListener();

如果你想,你可以從 Java 調用 Kotlin lazy

import kotlin.Lazy;

Lazy<SampleLifecycleListener> lazyListener = kotlin.LazyKt.lazy(() -> new SampleLifecycleListener()));
SampleLifecycleListener realListener = lazyListener.getValue();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM