zl程序教程

您现在的位置是:首页 >  其它

当前栏目

中缀表示法

表示法 中缀
2023-06-13 09:13:30 时间

无意苦争春,一任群芳妒。零落成泥碾作尘,只有香如故。——陆游

文档

中缀表示法能让我们定义一些“关键字”

标有 infix 关键字的函数也可以使用中缀表示法(忽略该调用的点与圆括号)调用。中缀函数必须满足以下要求:

infix fun Int.shl(x: Int): Int { …… } // 用中缀表示法调用该函数 1 shl 2 // 等同于这样 1.shl(2)

代码如下:

infix fun Int?.default(x: Int): Int = this ?: x
infix fun String?.default(x: String): String {
    return this ?: x
}

// 用中缀表示法调用该函数
1 default 0

// 等同于这样
null.default(0)

"1".default("x")

null.default("x")

效果: