Given a `reified R` I would like to return a defau...
# announcements
h
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?
Copy code
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
You'll have to do an unchecked cast here
h
naturalOrder
expects a
Comparable<R>
but AFAIK there's no way to indicate that
R
is
Comparable<R>
?
d
naturalOrder<Nothing>() as Comparator<R>
🎉 1
h
Thanks! Never would have thought to try that
d
Nothing
is a great tool if you're trying to fight the type system 😄
k
Or you could bound R to Comparable<R> if you want to operate only on comparable types
h
Can't do that unfortunately, it's possible
R
is not
Comparable<R>
.