打印中缀函数结果时,简单的kotlin示例打印kotlin.Unit
我有以下非常简单的kotlin代码来演示infix函数包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
,这是你的程序打印。