[SOLVED] What are the differences between kotlin variable functions and common fun functions?

Issue

There is a fun method0:

    private fun method0() {
        println("method0 fun")
    }

And a var method0 :

    var method0 = {
        println("method0")
    }

It seems they are used the same:

    method0()

I found that both occur at the same time, and the fun function has a higher priority when the code calls.
Other than that, is there any difference between them?

Solution

The var way of doing it results in a functional object. The lambda content is wrapped as a functional object so it can be passed around like any other instance of a class. It can directly be used as a function parameter, for instance.

var method0 = {
    println("method0")
}

fun doSomethingTwice(action: ()->Unit) {
    repeat(2) { action() }
}

fun main() {
    doSomethingTwice(method0)
}

And since it’s marked as a var you can swap it out for a different function:

fun main() {
    method0 = { println("hello, world!") }
    doSomethingTwice(method0)
}

Note that this way of specifying a function is a little bit heavier since it is wrapping the function in another class instance.

And you can still wrap any "regular" function into a functional object at any time by using :: to avoid doing it until it’s necessary.

fun method0() {
    println("method0")
}

fun main() {
    doSomethingTwice(::method0)
}

Answered By – Tenfour04

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *