https://kotlinlang.org logo
Title
h

hudsonb

11/29/2018, 1:44 PM
Given a
reified R
I would like to return a default comparator to use based on `R`s type. Is there any way to do something like this?
inline fun <reified R> defaultComparator(): Comparator<R>? = when {
    R::class.isSubclassOf(Comparable::class) -> naturalOrder<R>()  // Error: Type arg not within bounds
    // ... others
    else -> null
}
d

diesieben07

11/29/2018, 1:47 PM
You'll have to do an unchecked cast here
h

hudsonb

11/29/2018, 1:51 PM
naturalOrder
expects a
Comparable<R>
but AFAIK there's no way to indicate that
R
is
Comparable<R>
?
d

diesieben07

11/29/2018, 1:53 PM
naturalOrder<Nothing>() as Comparator<R>
🎉 1
h

hudsonb

11/29/2018, 1:58 PM
Thanks! Never would have thought to try that
d

diesieben07

11/29/2018, 1:59 PM
Nothing
is a great tool if you're trying to fight the type system 😄
k

Katya Yurukova

11/29/2018, 2:04 PM
Or you could bound R to Comparable<R> if you want to operate only on comparable types
h

hudsonb

11/29/2018, 4:04 PM
Can't do that unfortunately, it's possible
R
is not
Comparable<R>
.