Estoy siguiendo un tutorial en el sitio para desarrolladores de Android. Utiliza Kotlin en el ejemplo de Java. Encontré esta publicación en el desbordamiento de pila sobre un equivalente pero no entiendo las respuestas.
El código original es:
// 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: StringLo he reescrito de la siguiente manera:
// 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;¿Es esta respuesta demasiado simple? ¿O hay una traducción más compleja a Java?
lateinit en Kotlin es simplemente algo que juega con la nulabilidad de una variable. Dado que Java no tiene esa propiedad, no puede convertir literalmente lateinit a Java. Bueno, puede forzar su tipo pero no podrá aplicar @NonNull / @Nullable .
Lateinit y Lazy son excelentes temas de Kotlin para leer y profundizar. Espero que sigas aprendiendo sobre ellos.
La respuesta fue correcta: simplemente use private String lookupKey; y eso es.
Por cierto, lateinit solo crea una condición if en el código de bytes que arrojará si es nulo. No tiene lateinit en Java, por lo que el código debería hacerse a mano. Es solo otra buena característica que Kotlin tiene sobre Java.
La lateinit var lookupKey en Kotlin definió una propiedad sin un valor establecido directamente. El valor se establece en la propiedad más tarde. El compilador se encarga de agregar aserciones para asegurarse de que no sea posible leer el valor antes de que no se inicialice. https://kotlinlang.org/docs/reference/properties.html#late-initialized-properties-and-variables
El lateinit juega muy bien con la nulabilidad en Kotlin. Por lo tanto, puede definir una variable no anulable sin un valor en lugar de tener una variable anulable y controles nulos. https://kotlinlang.org/docs/reference/null-safety.html
La versión del código de Java no es equivalente a la versión de Kotlin: pierde la afirmación de verificación y permite valores null