Guys I started the KTor tutorial and in the very b...
# getting-started
e
Guys I started the KTor tutorial and in the very begginiing I got lost. I cannot understand what means
fun Route.customerRouting().
It means I am “injecting”
customerRouting()
function into
Route
class? Also, what is exactly the second parameter of this function:
public fun Route.route(path: String, build: Route.() -> Unit)
. I am a java developer and some aspects of kotlin are a bit weird for me
j
This function is called an extension function (you can look it up in Kotlin docs). You're not technically injecting the function into that class. You're declaring this function separately, and it can be imported separately (depending on it's visibility). The
Route
here is called the receiver of the extension function. It's really like other arguments. The only difference between a regular parameter and a receiver is how the argument is passed on the call site (it's just on the left instead of in the brackets, or it can be coming from an implicit
this
) and how the parameter is used in the body of the function (it's an implicit
this
)
👍 1
e
Thanks @Joffrey
a
the second parameter is a function signature, so you can pass lambdas and function references to it
k
The fact the
build
is declared as
Route.() -> Unit
means that if you pass a lambda expression to the function
Route.route
, then inside the body of your lambda expression you can refer to
this
(either explicitly or implicitly) as the object that is passed to your lambda function as the receiver argument.
j
I really invite you to take a look at Kotlin’s documentation before diving into Ktor, otherwise you will have a hard time. It’s like trying to use Spring without knowing Java, not impossible, but quite hard… Read at least the basics and the Idioms, there are small articles. You can learn more by looking at the whole documentation under the “Concepts” section in the sidebar.
1
a
I second the Kotlin official docs! They’re well written and appropriately thorough
1