Kotlin - println使用字符串模板到stderr

mjl*_*lee 8 kotlin

如何发送输出println()System.err.我想使用字符串模板.

val i = 3
println("my number is $i")
Run Code Online (Sandbox Code Playgroud)

println()消息发送到stdout,看起来没有选项发送到stderr.

zsm*_*b13 6

你可以像在Java中那样做:

System.err.println("hello stderr")
Run Code Online (Sandbox Code Playgroud)

标准的stdout输出只是通过Kotlin中的一些辅助方法得到特殊的较短版本,因为它是最常用的输出.你也可以使用完整的System.out.println表格.


Lyn*_*nAs 5

为什么不创建一个全局函数

fun printErr(errorMsg:String){
   System.err.println(errorMsg)
}
Run Code Online (Sandbox Code Playgroud)

然后从任何软件调用它

printErr("custom error with ${your.custom.error}")
Run Code Online (Sandbox Code Playgroud)


Mat*_*uth 5

不幸的是,科特林没有提供无处不在的写信方式stderr

如果您将Kotlin用作JVM,则可以使用与Java中相同的API。

System.err.println("Hello standard error!")
Run Code Online (Sandbox Code Playgroud)

如果使用Kotlin Native,则可以使用打开stderr的功能,并使用platform.posix软件包手动对其进行写入。

val STDERR = platform.posix.fdopen(2, "w")
fun printErr(message: String) {
    fprintf(STDERR, message + "\n")
    fflush(STDERR)
}

printErr("Hello standard error!")
Run Code Online (Sandbox Code Playgroud)