Kotlin - println using string template to stderr

Viewed 12687

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.

4 Answers

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) {
    platform.posix.fprintf(STDERR, "%s\n", message)
    platform.posix.fflush(STDERR)
}

printErr("Hello standard error!")

Note: Using formatting function printf may have security implications. Format string vulnerability can crash your application and you may want to consider using _s "secure" variant of printf function.


In multi-platform projects one can use mechanism of expect and actual function to provide single interface to write to STDERR on 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

Related