kotlin: How to compare Comparable<T> ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

kotlin: How to compare Comparable<T> ?

https://code.sololearn.com/cNk7ItRZQCBC/?ref=app

8th Sep 2018, 1:50 PM
libill
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
9th Sep 2018, 3:52 PM
John Wells
John Wells - avatar
+ 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.
9th Sep 2018, 3:02 PM
John Wells
John Wells - avatar
+ 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.
9th Sep 2018, 4:11 PM
John Wells
John Wells - avatar
+ 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.
9th Sep 2018, 4:14 PM
John Wells
John Wells - avatar