Is it possible to use higher order functions with optional arguments

I put together a fictitious problem to illustrate my point: let's say that we have the following convenient function for displaying information about a specific sorting algorithm:

fun sort(name: String, array: Array<Int>, sortingAlgorithm: (Array<Int>) -> Array<Int>) {
    println(name)
    sortingAlgorithm(array).forEach { print(" $it ") }
    println()
}

You would use it as follows:

sort("Selection Sort - Θ(n^2)", arrayOf(2, 3, 1), ::selectionSort)

And this works because the signature selectionSortis simple:fun selectionSort(array: Array<Int>): Array<Int> {

But I will say that I have a different sorting algorithm with the following signature

fun quickSort(array: Array<Int>,
              start: Int = 0,
              end: Int = array.size - 1): Array<Int> {

The last two arguments are optional, so theoretically you can call quickSortas you call selectionSort. That is, he respects the signature (Array<Int>) -> Array<Int>Right?

Unfortunately, when I try to call sort("Quick Sort", arrayOf(2, 3, 1), ::quickSort), I get:

missmatch type

, , , . , sort ?

+4
1

, :

  • 1) ( )
  • 2) - ( )

, , , :

val algorithm = ::quickSort
sort("Quick Sort", arrayOf(2, 3, 1), algorithm)

sort("Quick Sort", { quickSort(unsorted) }) Kotlin, .

+4

Source: https://habr.com/ru/post/1679748/


All Articles