Infix notation and with(…) does not work as I expe

2019-05-04 18:31发布

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?

2条回答
神经病院院长
2楼-- · 2019-05-04 19:08

This restriction is necessary for the parser to parse the code without conflicts with other syntax.

查看更多
再贱就再见
3楼-- · 2019-05-04 19:24

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.

查看更多
登录 后发表回答