Well, <out TypeVariable(T)>
is related to some advanced concepts such as generics and other things related to it, as you still learning kotlin fundementals, it is very OK you could not understand this message for now.
In general, the reason behind this message is that you didn't specify the element you are searching for, there is a parameter called element
should be there, the type of it is T
, T
here means a generic type, it accepts any class whether Int, String, anything, but it make since to put Int type in the parameter because your Array consist of Integers, otherwise en exception will be thrown.
For the Comperator
, you can set it with the value compareBy { it }
to compare the integers, and of course using IntArray
is better in your case, more efficient, and simpler. So, use Array
type only for non-primitive types. The reason behind specifying Comperator shines when you have a list of objects and you want to compare based on a property of these objects. But for Int type, use IntArray and everything will be good.
What is 'out' keyword?
Documentation:
https://kotlinlang.org/docs/generics.html#type-projections
Another question in stackoverflow about it:
What is out keyword in kotlin
What is the mean of compareBy { it }
above ?
This function is used to specify the property you want to use to compare the array elements, since your Array is of Int type, it
here is Int type, it means compare array elements by integer values.
To make it clearer, let us create a simple class called Book
:
class Book(
val title: String,
val pages: Int
)
Suppose you have an array of books that are sorted according to the pages number, and you want to do a binary search, here we are using compareBy
to tell the compiler to use pages number to compare the books, so it performs the comparisons properly:
val book1 = Book("Learn Kotlin", 100)
val book2 = Book("Learn Java", 200)
val books = arrayOf(book1, book2)
val index = books.binarySearch(element = book2, comparator = compareBy { it.pages }, fromIndex = 0, toIndex = books.size)
println(index) //prints 1
Look at compareBy { it.pages }
, it
is of type Book, and we are specifying .pages
to compare books based on their pages.