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?
fun evenFnis a method;val evenFnis 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.