How to get a platform-specific newline in Kotlin Multiplatform?
Asked Answered
D

1

7

I am seeking a function which returns a platform-specific newline string. I'm aware of System.lineSeparator(), which is only available in Kotlin/JVM, but there's a need for a multi-platform equivalent.

I'm also aware of the expect/actual approach, but I'm searching for a shorter way. (Maybe a function in the standard library?)

Dynah answered 23/12, 2021 at 9:23 Comment(1)
As far as I know, there is no such thing in kotlin stdlib. Maybe, some part of kotlin.text library might be used to create something similar manually. If you think that something like that would be useful, consider filing a feature request at kotl.in/issue.Legwork
A
-4

Something like this should do the trick:

val newLine = "\n"
Aliber answered 23/12, 2021 at 10:29 Comment(7)
How is that platform-specific? (That means it should return e.g. \n on Unix-like OSs, \r\n on Windows, &c.)Gravimetric
If you write this in common module, it should get translated to correct value on respective platform. No need for expect-actual for this.Aliber
How would it get translated?Gravimetric
By the Kotlin native compiler when it builds native code for respective platform.Aliber
@Gravimetric This answer is actually partially correct. In Kotlin/Native, println calls a C++ function konan::consoleWriteUtf8("\n", 1) and the single character '\n' gets translated on Windows to \r\n deep inside the C++ standard library (or the C library that the C++ library calls). Granted, it ought to be much more detailed.Need
To be clear, the val newLine = "\n" is only good if you write it in the Native modules, not the common module. For example, in Kotlin JVM this won't work; you need System.lineSeparator(). I don't know about JS.Need
See my full answer to a similar question: https://mcmap.net/q/1630312/-in-kotlin-multiplatform-how-can-i-read-line-separator-39-s-lengthNeed

© 2022 - 2024 — McMap. All rights reserved.