What is this syntax?`"creating and linking nodes" ...
# getting-started
t
What is this syntax?
"creating and linking nodes" example {
I don't understand how there's a string
"creating and linking nodes"
then after a
example
Please explain!
Copy code
fun main() {
    "creating and linking nodes" example {
        val node1 = Node(value = 1)
        node1.next = node3 // shortened for brevity
        println(node1)
    }
}
d
example
is probably an infix extension function on
String
that takes a lambda as parameter:
Copy code
infix fun String.example(body: () -> Unit) = TODO()

"foo" example { /* this is a lambda*/  }
m
someone created an infix extension function on String called example that takes a function.
t
Thank you! What would would be the
TODO()
in this case. Can you please provide a code example for it so that I could run it and try out. The code is this: https://pl.kotl.in/4_v-ixPxw
d
TODO
is a built-in kotlin function that just always throws an exception and has return type
Nothing
so you can put it in place of a missing implementation and have your code still compile.
t
I tried this with your suggestion:
Copy code
infix fun String.example(body: () -> Unit): Nothing = TODO()

fun main() {
    "creating and linking nodes" example {
        val node1 = Node(value = 1)
        val node2 = Node(value = 2)
        val node3 = Node(value = 3)
        node1.next = node2
        node2.next = node3
        println(node1)
    }
}
But got an error:
Copy code
Exception in thread "main" kotlin.NotImplementedError: An operation is not implemented.
	at experimentation.linkedlistyo.NodeKt.example(Node.kt:13)
	at experimentation.linkedlistyo.NodeKt.main(Node.kt:16)
What am I missing here?
d
Yes, that's what
TODO()
does, it throws
NotImplementedError
if you actually call th efunction
Its a placeholder for code you have not written yet that allows your code to still compile, even though it is not completed.
t
Yes but what was expected here was for the code to atleast do print output using
println()
in the main function. So as its not printing and just throwing error with
TODO()
It's not as desired though.
d
The
println
is inside a lambda, which you never call. As such the code within the lambda is never executed.
m
Take doesn't know what you want example to do, so it used TODO. You need to know what the body is supposed to do and implement that
If you just want it to call the lambda then you do
infix fun String.example(body: () -> Unit): Nothing = body()
t
This worked!
infix fun String.example(body: () -> Unit): Unit = body()
Thank you for guidance!
m
I think you’re trying to have us solve some exercise or assignment of yours… 😉
t
Was reading a book where author did not explain it.
m
oky doky