Am I correct that using 1.4 the correct replacemen...
# announcements
p
Am I correct that using 1.4 the correct replacement of
x.maxBy { ...}!!
is
x.maxByOrNull { ...}!!
and that there is no replacement that throws if the result is null?
b
maxOf throws, maxOfOrNull returns null
p
I meant maxBy
b
Yeah, me too ­čśä
x.maxBy { ...}!!
is redundant as it'll never return null
p
Yes, it will, it's nullable
I.e if we have:
Copy code
fun test() {
  data class Person(val age: Int)
  val oldestPerson: Person = listOf(Person(42), Person(12))
    .maxBy { it.age }!!
}
Thats deprecated (and still nullable)
Copy code
@Deprecated("Use maxByOrNull instead.", ReplaceWith("maxByOrNull(selector)"))
@DeprecatedSinceKotlin(warningSince = "1.4")
public inline fun <T, R : Comparable<R>> Iterable<T>.maxBy(selector: (T) -> R): T? {
    return maxByOrNull(selector)
}
b
My bad, maxBy is now deprecated. In that case there's no throwing option other than just x.maxByOrNull { ...}!!
Which means you were correct all along and I was just leading you astray ­čśä
p
There is maxOf but that returns the type of the lambda
And it throws a NoSuchElementException which is what I want. In these cases a NPE isn't hiding the underyling fact that I want to get sth from the list thats not there
b
x.maxByOrNull { ...} ?: throw MyAwesomeError()
?
a
It should come in 1.6 as far as I know https://youtrack.jetbrains.com/issue/KT-38854
s
If this is a common pattern in your code, you can easily implement a function for it yourself as @Big Chungus suggested.
p
The missing link was the ticket posted by @arekolek without that the whole change made no sense for me. I expect that there will be an inspection with a quick fix once 1.6 hits