Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - println using string template to stderr

Tags:

kotlin

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.

like image 343
mjlee Avatar asked May 27 '17 19:05

mjlee


2 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) {
    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

like image 188
Matej Kormuth Avatar answered Jan 03 '23 06:01

Matej Kormuth


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.

like image 40
zsmb13 Avatar answered Jan 03 '23 04:01

zsmb13