Reputation: 923
I am actually new to kotlin language, so this can be basic question, but I cannot find a reasonable answer.
According to resources I read, (Int) -> T is a function type which takes an integer parameter and returns anything; that's why, I defined a function like this :
fun square( arg : Int ) : Int{
return (arg * arg)
}
After that, I tried to pass reference of this function to the second argument of the constructor of Array class in kotlin. This attempt results in an error. The error says that there is a type mismatch.
var arr : Array<Int> = Array(5, square)
I cannot understand why I faced such an error. Can anyone explain me ?
Upvotes: 2
Views: 142
Reputation: 81929
You're almost there, try this one:
Array(5, ::square)
Function references use the ::
operator.
You can also make use of lambdas, which feels more idiomatic:
Array(5, { it * it } )
Not that this is equivalent to the following because when a lambda is the last argument passed to a function, it can be lifted out of the parentheses:
Array(5) { it * it }
Upvotes: 3