How do I send output of println()
to System.err
. I want to use string template.
val i = 3
println("my number is $i")
println()
sends message to stdout and it looks like there is no option to send to stderr.
Kotlin unfortunately does not provide ubiquitous way to write to stderr
.
If you target JVM with Kotlin you can use the same API as in Java.
System.err.println("Hello standard error!")
In case of Kotlin Native you can use a function that opens the stderr and writes to it manually with the use of platform.posix
package.
val STDERR = platform.posix.fdopen(2, "w")
fun printErr(message: String) {
fprintf(STDERR, message + "\n")
fflush(STDERR)
}
printErr("Hello standard error!")
In multi-platform projects one can use mechanism of expect
and actual
function to provide single interface to write to STDERR in all platforms.
// Common
expect fun eprintln(string: String): void
// JVM
actual fun eprintln(string: String) = System.err.println(string)
https://kotlinlang.org/docs/reference/platform-specific-declarations.html
You can just do it like you would in Java:
System.err.println("hello stderr")
The standard stdout output just gets the special shorter version via some helper methods in Kotlin because it's the most often used output. You could use that with the full System.out.println
form too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With