0
kotlin: How to compare Comparable<T> ?
4 Answers
+ 6
Your issue with compareTo is because of the way generics handle the type. Your best bet would be to pass in a comparison lambda to perform your test.
https://code.sololearn.com/crO2Jrn6445x
+ 4
Comparable is an abstract class. It must be inherited to be used. The Char class already inherits from Comparable so just using it would be fine.
+ 4
Generics strip types down to things that all types have. Nothing more can be used without proving it is of the type. You could do something like this:
fun more(a: T, b: T): Boolean {
when {
a is Char && b is Char ->
return a.compareTo(b) > 0
a is Int && b is Int ->
return a.compareTo(b) > 0
a is Double && b is Double ->
return a.compareTo(b) > 0
a is String && b is String ->
return a.compareTo(b) > 0
}
}
However, there would be no way to know every data structure the user of your generic might call you with. Requiring the comparison as an argument guarentees your code works.
+ 3
They could pass array of a data class with 4 integers and a string calling with a string sort the first time and an integer the next.