1 Why it doesn't compile?
val sum = {x, y -> x + y}
println(sum(1,2))
code from http://confluence.jetbrains.net/display/Kotlin/Function+literals
is there any plan for local type inference for lambdas?
2 What benefits from local functions
fun main(args:Array<String>){
val sum = {(x : Int, y : Int) : Int -> x + y}
fun sum2(x:Int, y:Int):Int {return x + y}
}
if language already have lambdas?
1. Seems to be a bug in the docs. Thanks
BTW, what type would you expect 'sum' to be?
- This makes the language more regular: I can have a function anywhere I like.
Your argument can be extended to “why have functions at all when we can have val’s of function types?”, and this approach does not seem right.
1) Int -> Int
Nemerle, for example, have this feature, type inference by usage.
def sum(x,y) { x + y } doesn't compile
but if local function is used sum(1,2) it's clear what type it has
Nemerle's type inference is indeed very powerful (and, as a consequence, rather slow). Kotlin aims for a simpler (faster and more predictable) type inference algorithm.
fun <T,K,R> Tuple2<T,K>.apply(func: Function2<T,K,R>) : R {
return func(this._1, this._2)
}
Is it really
val sum = {x, y -> x + y}
sum(1,2)
more complex then current type inference?
val r =#(1,2).apply({x,y -> x + y})
Local functions are changed often, is’t annoying change it’s type every time.
Yes, it is much more complex, because instead of a single call expression we have to analyze the whole local scope.