gpt4 book ai didi

kotlin - 简单的 kotlin 示例在打印中缀函数结果时打印 kotlin.Unit

转载 作者:行者123 更新时间:2023-12-01 23:01:37 31 4
gpt4 key购买 nike

我有以下非常简单的 kotlin 代码来演示中缀函数 com.lopushen.demo.presentation 包

fun main(args: Array<String>) {
print("Hello " x_x "world")
}


infix fun String.x_x(s: String) {
println("$this x_x $s x_x")
}

预期结果是

Hello  x_x world x_x
Process finished with exit code 0

实际结果如下,是什么原因导致程序打印kotlin.Unit?

 Hello  x_x world x_x
kotlin.Unit
Process finished with exit code 0

最佳答案

您的程序中有两个打印语句。 x_x 函数中的一个打印“Hello world”字符串,main 中的一个打印 x_x 函数的返回值。该函数没有任何 return 语句或声明的返回类型,因此 Kotlin 推断 Unit 作为其返回类型。 Unit 类型有一个值 kotlin.Unit,这是您的程序打印的内容。

关于kotlin - 简单的 kotlin 示例在打印中缀函数结果时打印 kotlin.Unit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43217825/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com