Kotlin-使用字符串模板将println转换为stderr
如何将Kotlin-使用字符串模板将println转换为stderr,kotlin,Kotlin,如何将println()的输出发送到System.err。我想使用字符串模板 println() 您可以像在Java中一样: System.err.println("hello stderr") 标准stdout输出只是通过Kotlin中的一些helper方法获得了特殊的较短版本,因为它是最常用的输出。您也可以将其与完整的System.out.println表单一起使用。如果您想像Kotlin中的Java一样打印错误,请检查以下代码: System.err.println("Printing
println()
的输出发送到System.err
。我想使用字符串模板
println() 您可以像在Java中一样:
System.err.println("hello stderr")
标准stdout输出只是通过Kotlin中的一些helper方法获得了特殊的较短版本,因为它是最常用的输出。您也可以将其与完整的System.out.println
表单一起使用。如果您想像Kotlin中的Java一样打印错误,请检查以下代码:
System.err.println("Printing Error")
它将以红色打印
但如果只使用println()
,则其工作原理如下:
System.out.println("Printing Hello")
为什么不创建一个全局函数呢
fun printErr(errorMsg:String){
System.err.println(errorMsg)
}
然后从anyware调用它
printErr("custom error with ${your.custom.error}")
不幸的是,Kotlin没有提供无处不在的写入stderr
的方法
如果使用Kotlin以JVM为目标,则可以使用与Java中相同的API
System.err.println("Hello standard error!")
如果是Kotlin Native,您可以使用一个函数打开stderr,并使用platform.posix
package手动写入
val STDERR = platform.posix.fdopen(2, "w")
fun printErr(message: String) {
fprintf(STDERR, message + "\n")
fflush(STDERR)
}
printErr("Hello standard error!")
在多平台项目中,可以使用expect
和actual
函数的机制,在所有平台中提供单个接口来写入STDERR
// Common
expect fun eprintln(string: String): void
// JVM
actual fun eprintln(string: String) = System.err.println(string)
我应该说清楚的。我想使用字符串模板。字符串插值不仅限于println
函数,而且在kotlin中随处可见。大多数情况下不用说,但这对其他kotlin平台(例如native)没有帮助。问题是2017年开始的,它特别询问JVM,写入System.err
。与上面的一些其他答案相同:这在Kotlin native中不起作用。科特林!=Kotlin/JVM
// Common
expect fun eprintln(string: String): void
// JVM
actual fun eprintln(string: String) = System.err.println(string)