缀符号和with(...)不能按我预期的那样工作 [英] Infix notation and with(...) does not work as I expected

查看:66
本文介绍了缀符号和with(...)不能按我预期的那样工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下情形:我有一个课程测试

Consider the following scenario: I have a class Test

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

和主要方法

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

如您所见,我正在测试中缀符号.考虑到 with(...),您可以使用在 with 块中作为参数传递的对象无需通过点表示法访问其成员,我希望该前缀表示法可以像在上面的示例中所示那样工作.

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.

不幸的是,这不起作用,是否有理由为什么不起作用?它是一个错误还是仅仅是一个限制?还是我没有正确解释 with(...)函数?

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?

推荐答案

中缀表示法是关于其使用方式的语法.它与左侧的对象和右侧的参数一起使用.

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.

这篇关于缀符号和with(...)不能按我预期的那样工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆