我正在关注 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/