Why are there two functions which do the exact same thing? Why must be invoked differently in Kotlin?

121 Views Asked by At
fun main() {
    fun evenFn(num: Int): Boolean {
        return num % 2 == 0
    }
    val evenFn = fun(num: Int) = num % 2 == 0
    val list = listOf(1, 2, 3, 4, 5, 6)
    println(list.filter(evenFn))
    println(list.filter { evenFn(it) })
}

How is it that I can declare two evenFns with the same name (one is stored in a variable and the other is just defined) and I have to invoke them in different ways? In JavaScript, doing so would throw an error saying that there is already an evenFn.

Can someone explain why the two evenFns are treated different by the compiler?

3

There are 3 best solutions below

0
Alexey Romanov On BEST ANSWER

fun evenFn is a method; val evenFn is a local variable which happens to have a function type. In Kotlin (and Java, and C#, etc. etc.) it's allowed to have a method and a local variable with the same name in scope, and the type of the local variable doesn't affect these rules.

1
Matt On

Doing so in Javascript wouldn't throw an error. In Javascript functions are hoisted to the top of the scope.

If you were to write code such as

var test = function() { 
    console.log('a');
}

function test() {
    console.log('b');
}

test();
test.apply();

the second function definition would be hoisted to the top to create code that reads as

var test = function() { console.log('b'); }
var test = function() { console.log('a'); }

As you can see, the function definition is overwritten by the variable definition. The output would therefore be

a
a
0
Shubhang B On

I figured it out, after reading the Function types section of the kotlin documentation. You need a callable reference to local functions , member functions to pass them around as references.