Skip to content

Instantly share code, notes, and snippets.

@igorlukanin
Last active October 10, 2015 08:25
Show Gist options
  • Save igorlukanin/8de0cfcbb9fd15905ef6 to your computer and use it in GitHub Desktop.
Save igorlukanin/8de0cfcbb9fd15905ef6 to your computer and use it in GitHub Desktop.
There's nothing wrong with nulls if you have proper types :)
fun max<T : Any>(list: List<T>, weight: (T) -> Int): T? {
return when (list.size()) {
0 -> null
1 -> list.first()
else -> list.reduce({ a, b -> if (weight(a) > weight(b)) a else b })
}
}
fun main(args: Array<String>) {
println( max(listOf("a", "bcd", "ef"), { it.length() }) )
println( max(listOf("a"), { it.length() }) )
println( max(emptyList<String>(), { it.length() }) )
println( max(emptyList<String>(), { it.length() }) ?: "default" )
}
@igorlukanin
Copy link
Author

Play with it at try.kotlinlang.org.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment