https://kotlinlang.org logo
#announcements
Title
# announcements
t

tipsy

08/01/2017, 4:44 PM
can this be written simpler?
Copy code
fun mapKeysOrReturnNullIfAnyNulls(keys: Array<out String>, f: (s: String) -> String?): List<String>? = try {
    keys.map { f.invoke(it) }.requireNoNulls().toList()
} catch (e: IllegalArgumentException) {
    null
}
m

michaelsims

08/01/2017, 4:52 PM
If you don't mind suppressing an unchecked cast warning:
Copy code
@Suppress("UNCHECKED_CAST")
fun Array<out String>.mapKeysOrReturnNullIfAnyNulls(f: (s: String) -> String?): List<String>? =
    map(f).takeIf { it.all { it != null }} as List<String>?
2 Views