Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infix notation and with(...) does not work as I expected

Consider the following scenario: I have a class Test

class Test() {
    infix fun say(msg: String) = println(msg)
}

and a main method

fun main(args: Array<String>) {
    val test = Test()

    test say "Hello World!" //Works

    with(test) {
        say "Goodbye World!" //Does not work
        say("Hello again!") //Works
    }
}

As you can see I'm testing out the infix notation. Considering with(...) allows you to work with the object passed as parameter in the with block without having to access its members through the dot notation, I would expect the infix notation to work like I show in my example above.

Unfortunately this does not work, is there a reason why this does not work? Is it a bug or simply a limitation? Or perhaps I am not interpreting the with(...) function correctly?

like image 303
Limnic Avatar asked Mar 13 '23 22:03

Limnic


1 Answers

Infix notation is about the syntax of the way it's used. It works with an object on the left and the parameter on the right.

When using with you no longer have an object token on the left, so the special syntax for infix notation no longer works. You have to fall back to the regular function notation.

like image 54
Doug Stevenson Avatar answered Mar 19 '23 03:03

Doug Stevenson