Home > Enterprise >  Kotlin Data Structures and Algorithms
Kotlin Data Structures and Algorithms

Time:06-09

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)
}

"push" example {
    val list = LinkedList<Int>()
    list.push(3)
    list.push(2)
    list.push(1)
    println(list)
}

}

So, I'm following Data Structures and Algorithms for Kotlin, First Edition (there's now a Second).

What does the "creating and linking nodes" example {} or the "push" example {} do, exactly? It is being rejected by the IDE and is definitely not syntax I've seen. Is this old syntax, deprecated? If I just remove it, and keep the code contained within the example{}, it appears to work fine, as intended. Can anyone tell me why I should or would want to keep this?

The following works fine, as far as I can tell, and... for now.

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)


// "push" example {}
    val list = LinkedList<Int>()
    list.push(3)
    list.push(2)
    list.push(1)
    println(list)

}

enter image description here

enter image description here

CodePudding user response:

Only with that... My bet is that example is an infix function

Adding something like

infix fun String.example(block: () -> Unit) : block()

should make it work

  • Related