Marian Schubert
06/03/2019, 6:53 PMjava.io.File.listFiles
returns null sometimes?Sergey Bondari
06/03/2019, 6:55 PMval files: List<Files>? = java.io.File.listFiles()
?Sergey Bondari
06/03/2019, 6:56 PMjava.io.File.listFiles()?.let { notNullVal -> …}
?tseisel
06/03/2019, 7:39 PMinline fun java.io.File.listFilesOrNull(): List<File>? = listFiles()
This way, both the function name and its signature warns about a potentially null
return value, and the compile will force you to handle it.tseisel
06/03/2019, 8:56 PMSergey Bondari
06/03/2019, 9:58 PMtseisel
06/04/2019, 6:09 AMlistFiles()
, making that extension function almost free. But the inline
modifier is not required for that solution to work.Marian Schubert
06/04/2019, 7:33 AMStephan Schroeder
06/04/2019, 9:13 AMval files: List<Files>? ...
the issue being that the function you’re calling comes from Java and therefore provides no nullability information (which makes it’s return-type the platform-type List<Files>!
which means “maybe it’s nullable, maybe it’s not”). So you as developer have to tell Kotlin that this function can return null by explicitly declaring its type as nullable (hence the ‘?’ in the type declaration).tseisel
06/04/2019, 9:16 AM@Nullable
, @NonNull
, @NotNull
, etc.
The Android SDK was updated to include those annotations wherever possible, making it easier to use it with Kotlin. But I don't think that the JDK will adopt those annotations... I don't think Oracle (that distributes the most used JDK implementation) would like to see Kotlin replace Java 😕Marian Schubert
06/04/2019, 11:29 AMAlexey Belkov [JB]
06/04/2019, 12:29 PMimport java.io.File
fun foo() {
val files = java.io.File("snth").listFiles()
bar(files) // [NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS] Type mismatch
}
fun bar(files: Array<out File>) {
}
Note that it's not a proper Kotlin compiler warning, even though it looks like it. It's only displayed in the IDE editor. You can try the 1.3.40 EAP right now: https://discuss.kotlinlang.org/t/kotlin-1-3-40-early-access-preview/12775Marian Schubert
06/04/2019, 12:39 PM