https://kotlinlang.org logo
Title
t

Tuang

09/25/2019, 8:58 AM
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

diesieben07

09/25/2019, 9:01 AM
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

Drasko Saric

09/25/2019, 9:31 AM
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

Tuang

09/25/2019, 9:46 AM
@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

Drasko Saric

09/25/2019, 9:51 AM
No. Let me explain.
a

Alowaniak

09/25/2019, 9:52 AM
if
sampleFun
would return a function itself then yes. But most probably
getOrPut("first arg", ::sampleFun)
or
getOrPut("first arg") { sampleFun(it) }
d

Drasko Saric

09/25/2019, 9:56 AM
@Alowaniak, yes, you are right, if
sampleFun
return function itself, but I think it is maybe confusing to @Tuang.
t

Tuang

09/25/2019, 9:57 AM
yeah, it’s a little bit confusing me,, if u have another idea please do share me @Drasko Saric
d

Drasko Saric

09/25/2019, 10:05 AM
There are two functions with same signature,
getOrPut
function and function used for calling
getOrPut
.
t

Tuang

09/25/2019, 10:12 AM
thanks @Drasko Saric I’ll be check
👍 1
thank you very much guys,,especially @Drasko Saric i understand now
👍 1
d

Drasko Saric

09/25/2019, 10:31 AM
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

Tuang

09/25/2019, 10:32 AM
Sure thing
m

Matteo Mirk

09/25/2019, 12:43 PM
@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

Alowaniak

09/25/2019, 1:03 PM
Also you might want to play around with using functions as variables
val myPrint: (x: Any) -> Unit = ::println
myPrint("foo")
👍 2