Higher Order Functions


#1

Hi,
I am learning kotlin and am not able to find exact difference between these two implementations.
implementation 1:
I have the following class and the method in my landing.kt file.

   fun calledMethod  (dummy1:Int,dummy2:String):(SampleClass,String,Long)-> Unit{
         println("level 1")
         val z=2
         return {c,a,b->
               println("level 2 $z")
         }
    }


    class SampleClass{

         init {
               println("level sampleclass")
         }
         fun getx()=22
         fun getY()=23
    }

and I invoke this method as such

fun main(args:Array<String>) {
         val setter = calledMethod(1, "dd")
         setter.invoke(SampleClass(),"ss",123L)
         println("Done!")
}

and the output is

level 1
level sampleclass
level 2 2
Done!

implementation 2:
The other implementation is

I am making a change to the function like this

fun calledMethod  (dummy1:Int,dummy2:String):SampleClass.(String,Long)-> Unit{
    println("level 1")
    val z=2
    return {a,b->
       println("level 2 $z")
    }
}

and the sample class is the same and the main method is also the same.
the output is

level 1
level sampleclass
level 2 2
Done!

which is also the same.

Now my doubt is what difference does this syntax make SampleClass.(String,Long)-> Unit over the regular higher order functions. This also adds a this variable to the invoked function. What does this syntax do. Can someone help me with this.


#2

The diference is that in the second example you are returning an extension function.
this in this case is the instance of SampleClass the extension will be called on.
This allows you to write SampleClass().setter("ss", 123L) instead of setter.invoke(SampleClass(),"ss",123L)

https://kotlinlang.org/docs/reference/extensions.html#extension-functions


#3

thank you so much @Eliote. I got it.


#4

And @Eliote can you help me with the non lambda implementation of calledMethod that creates an instance of SampleClass and call it’s extension function that accepts (String,Long) as integer and returns a Unit. Thanks in Advance


#5

Like that?

fun calledMethod(dummy1: Int, dummy2: String) {
	println("level 1")
	val z = 2
	val setter: SampleClass.(String, Long) -> Unit = { a, b ->
		println("level 2 $z")
	}
	SampleClass().setter("ss", 123L) // maybe? (dummy2, dummy1.toLong())
}

#6

Now it makes sense completely. thank you