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

不想你离开。 提交于 2019-12-22 07:54:22

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/35976405/infix-notation-and-with-does-not-work-as-i-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!