What does it mean to have a function that is invok...
# codereview
k
What does it mean to have a function that is invoked like
.map(::MyDto)
or
.map(::println)
?
j
::println
is a function reference.
map
is a higher order function, meaning that it takes a function as a parameter. A value of type function can be in different forms. You can pass a lambda expression like
{ println(it) }
, or you can pass a variable of a function type, or you can pass a reference to a function with this
::funName
syntax.
It's important to note that you're not directly calling
println
or the
MyDto
constructor and passing the result to
map
here, you're passing the function itself. This is what higher-order functions are all about.
k
Thank you for the explanation. Is it idiomatic kotlin to prefer high order functions over inline lambda expressions?
Also, how would you construct aligning functions that conform to higher order functions? Could you please provide a simple example?
j
Sorry I think there is some confusion here. The higher-order function here is
map
. The
::
syntax denotes a function reference. Now whether that is idiomatic is debatable. Lambdas are extremely common, and make no perf difference when the higher-order function is
inline
. Function references are less common I would say, because you can't use them if the signature of the function doesn't match with what the higher order function expects. I wouldn't say one is more idiomatic than the other, though.
Also, how would you construct aligning functions that conform to higher order functions? Could you please provide a simple example?
Sorry I don't get the question. Could you please elaborate?
By the way, I would suggest you get familiar with this topic from the docs: https://kotlinlang.org/docs/lambdas.html