java - Java翻译成 "private lateinit var lookupKey: String"是什么

标签 java android kotlin

我正在关注 tutorial在 Android 开发者网站上。它在 Java 示例中使用 Kotlin。我找到了这个 post堆栈溢出大约等价,但我不明白答案。

原代码为:

// 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 翻译?

最佳答案

Kotlin 中的

lateinit 只是处理变量的可空性的东西。由于 Java 没有这样的属性,您不能将 lateinit 直接转换为 Java。好吧,您可以强制其类型,但您将无法应用 @NonNull/@Nullable

Lateinit 和 Lazy 是 Kotlin 的重要主题,值得深入阅读。 我希望您能继续了解这些。

答案是正确的:只需使用 private String lookupKey; 就可以了。

顺便说一句,lateinit 只是在字节码中创建一个 if 条件,如果为 null 则抛出该条件。 Java 中没有 lateinit,因此需要手动编写代码。这只是 Kotlin 相对于 Java 的另一个不错的特性。

关于java - Java翻译成 "private lateinit var lookupKey: String"是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54930839/

相关文章:

java - 部署spark驱动程序应用程序而无需spark提交

java - 不使用 javax.net.debug 的 SSL 握手细节暴露

java - 从 src 目录打开文件 (Java)

android - 隐式属性类型是否与显式属性类型相同?

java - 黑名单 Maven 依赖项

android - BottomSheet + ViewPager2 拖动隐藏不起作用

java - 如何以编程方式正确调整 View 的大小,使其底部与 ConstraintLayout 中其他 View 的顶部对齐?

java - UTF-8 不适用于 Java zipOutputStream

android - 如何从 fragment 中拦截 MainActivity 的 BottomNavigationView 菜单点击

android - 如何存储自定义对象的数组列表?