Home > Mobile >  Kotlin call of a function
Kotlin call of a function

Time:06-06

 fun add ( value : A, compare : (A, A) -> Int ) : Tree <A> =
        when (this) {
            is Empty -> treeNode(value)
            is Node -> if (compare(value,this.value) < 1) {
                treeNode(this.value,left.add(value,compare),right)
            } else{
                treeNode(this.value,left,right.add(value,compare))
            }
        }

I dont understand what the funtion wants when I call it

tree.add(5,?)

CodePudding user response:

The second argument of tree.add() should be a function that takes 2 objects of type A and returns an integer.

In your case, the semantic is the same as the Comparator.compare function:

Compares its two arguments for order. Returns zero if the arguments are equal, a negative number if the first argument is less than the second, or a positive number if the first argument is greater than the second

To pass such a function, you can use a lambda expression (with braces):

tree.add(5, { a, b -> a - b })

In Kotlin, we usually pass such lambdas outside the parenthesis of the function call, though. Like this:

tree.add(5) { a, b -> a - b }

Note: passing the comparator as argument to add is rather bad design (especially because this function is public), because the comparator can be different for each call adding elements to the tree. It should instead be a property of the tree itself, otherwise the tree could become inconsistent.

  • Related