24人参与 • 2025-05-19 • C/C++
在 kotlin 中,使用 infix
关键字修饰的函数称为中缀函数,使用是可以省略 .
和 ()
,允许以更自然(类似自然语言)的语法调用函数,这种特性可以使代码更具可读性。
中缀函数必须满足以下条件:
infix
关键字;调用方法:
a.function(b)
;a function b
(省略点号和括号,增强可读性);示例:
class person(private val name: string) { // 成员中缀函数 infix fun say(message: string) { println("$name says $message") } } // 扩展中缀函数 infix fun int.multiply(factor: int): int = this * factor
反编译成 java 代码:
public final class person { private final string name; public final void say(@notnull string message) { intrinsics.checknotnullparameter(message, "message"); string var2 = this.name + " say " + message; system.out.println(var2); } public person(@notnull string name) { intrinsics.checknotnullparameter(name, "name"); super(); this.name = name; } }
底层实现:
infix
关键字允许省略 .
和括号 ()
;适用于需要代码接近自然语言的场景,例如 dsl(领域特定语言)设计:
infix fun <t> t.shouldequal(expected: t) { if (this != expected) throw assertionerror("excepted $expected, but got $this") } // 使用 actualvalue shouldequal expectedvalue
简化数学运算符或逻辑操作的表达:
infix fun int.pow(exponent: int): int = todouble().pow(exponent).toint() val result = 2 pow 3 // 等价于 2.pow(3)
kotlin 标准库中的 to
函数是典型的中缀函数:
val map = mapof( "name" to "eileen", "age" to 30 )
结合中缀函数和扩展函数实现链式调用:
infix fun string.concatwith(another: string) = "$this$another" // 链式中缀调用 val message = "hello" concatwith "world" concatwith "!"
public
或 internal
(默认,模块内可见);1 + 2 and 3 // 等价于 (1 + 2) and 3
kotlin 标准库广泛使用中缀函数。
用于创建 pair
对象:
infix fun <a, b> a.to(that: b): pair<a, b> = pair(this, that)
生成区间:
val range = 1 until 10 // 等价于 1.until(10)
例如 step
和 downto
:
for (i in 10 downto 1 step 2) { }
到此这篇关于kotlin 中 infix 关键字的原理和使用场景的文章就介绍到这了,更多相关kotlin infix 关键字内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论