Last active
October 10, 2015 08:25
-
-
Save igorlukanin/8de0cfcbb9fd15905ef6 to your computer and use it in GitHub Desktop.
There's nothing wrong with nulls if you have proper types :)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Play with it at try.kotlinlang.org.