what does this ` handler: (key: K) -> V?) ` mea...
# getting-started
t
what does this
handler: (key: K) -> V?)
means In the following function
fun getOrPut(key: String, handler: (key: String) -> V?)
i thinks
handler
is something likes the arguments name, so what are the rest? is it a lambda ?
d
handler
is a parameter with a function type. You could pass a lambda here, for example. https://kotlinlang.org/docs/reference/lambdas.html
👍 1
d
Simply put, function
getOrPut(...)
receives variable named
key
of type
String
, which will be used as argument (or variable which will be used for calculating the argument ) of function
handler(...)
when invoking.
t
@Drasko Saric thanks So, how to set the parameter when I call
getOrPut()
function. may be like this ?
getOrPut("first arg", sampleFun("first arg"))
d
No. Let me explain.
a
if
sampleFun
would return a function itself then yes. But most probably
getOrPut("first arg", ::sampleFun)
or
getOrPut("first arg") { sampleFun(it) }
d
@Alowaniak, yes, you are right, if
sampleFun
return function itself, but I think it is maybe confusing to @Tuang.
t
yeah, it’s a little bit confusing me,, if u have another idea please do share me @Drasko Saric
d
There are two functions with same signature,
getOrPut
function and function used for calling
getOrPut
.
t
thanks @Drasko Saric I’ll be check
👍 1
thank you very much guys,,especially @Drasko Saric i understand now
👍 1
d
I am glad to hear that. Now when you understand this, try to understand the thing that @Alowaniak said, i.e.
getOrPut("first arg", sampleFun("first arg"))
would make sense only when
sampleFun(..)
would return a function. 🙂
t
Sure thing
m
@Tuang, just to answer more precisely to your original question, what follows
handler
is just a type declaration (like
String
), only that it’s a function type, so it accepts any function reference. The function type specifies its input and output types. So like others showed above, that parameter can accept a function/method reference or a lambda.
👍 1
a
Also you might want to play around with using functions as variables
val myPrint: (x: Any) -> Unit = ::println
myPrint("foo")
👍 2