在Java中,“private lateinit var lookupKey: String”是什么意思?

3

我正在按照Android开发者网站上的教程进行学习。这个Java示例中使用了Kotlin。我在Stack Overflow上找到了一篇帖子,讨论了一个等效的解法,但我不理解它们的答案。

原始代码如下:

// Defines the selection clause
private static final String SELECTION = Data.LOOKUP_KEY + " = ?";
// Defines the array to hold the search criteria
private String[] selectionArgs = { "" };
/*
 * Defines a variable to contain the selection value. Once you
 * have the Cursor from the Contacts table, and you've selected
 * the desired row, move the row's LOOKUP_KEY value into this
 * variable.
 */
private lateinit var lookupKey: String

我已经对其进行了改写,具体如下:

// Defines the selection clause
private static final String SELECTION = ContactsContract.Data.LOOKUP_KEY + " = ?";

// Defines the array to hold the search criteria
private String[] selectionArgs = { "" };
/*
 * Defines a variable to contain the selection value. Once you
 * have the Cursor from the Contacts table, and you've selected
 * the desired row, move the row's LOOKUP_KEY value into this
 * variable.
 */
private String lookupKey; 

这个答案太简单了吗?还是有更复杂的Java翻译方法?


不,就这样了。 - Zoe stands with Ukraine
这并不完全相同,因为一旦给 lateinit String 赋值,它就保证不会是 null。您可以在 Android Studio 的工具菜单中找到对应的 Java 代码,然后选择 Kotlin -> 显示 Kotlin 字节码 -> 反编译。 - Michael
2个回答

5
在 Kotlin 中,lateinit 只是在处理变量的可空性方面起作用。由于 Java 没有这样的属性,你不能直接将 lateinit 转换成 Java。但是,你可以强制其类型,但无法应用 @NonNull/@Nullable
关于 Kotlin 中的延迟初始化和懒加载,这是非常好的主题,值得深入了解,希望您能继续学习。
答案是正确的:只需使用 private String lookupKey; 就可以了。
顺便说一下,lateinit 只会在字节码中创建一个判断条件,如果为空则会抛出异常。在 Java 中并没有 lateinit,因此该代码需要手动编写。这只是 Kotlin 相对于 Java 的又一个不错的特性。

1
在 Kotlin 中,lateinit var lookupKey 定义了一个没有直接设置值的属性。该值稍后会被设置到属性中。 编译器会添加断言来确保在属性初始化之前无法读取该值。 https://kotlinlang.org/docs/reference/properties.html#late-initialized-properties-and-variables lateinit 在 Kotlin 中与 nullability 很好地协作。因此,您可以定义一个非空变量而不是具有可空类型和空检查的变量。 https://kotlinlang.org/docs/reference/null-safety.html Java 代码版本与 Kotlin 版本不相等——它缺少检查断言并允许 null 值。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接