javascriptkotlinkotlin-multiplatformkotlin-native

In Kotlin multiplatform, how can I read line separator's length?


On JVM I can use the following:

fun lineSeparatorLength(): Int = System.getProperty("line.separator").length

Can someone show me how to implement the same for Native/Desktop and JS?


Solution

  • The answer will be mostly the same as the previous one but with more details and the modern KMP approach. In your common source set, you may have the next code:

    // commonMain/src/.../lineSeparator.kt
    expect val lineSeparator: String
    
    val lineSeparatorLength = lineSeparator.length
    

    And after each target, you need to define the actual declaration. For JVM (as you mentioned), it would look like this

    // jvmMain/src/.../lineSeparator.jvm.kt
    actual val lineSeparator = System.getProperty("line.separator")
    

    For the JS target, it would look like this:

    // jsMain/src/.../lineSeparator.js.kt
    
    actual val lineSeparator = runCatching { js("require('os')") }?.EOL // for Node.js
      ?: "\n" // in a browser, it's always UNIX-style line endings, as far as I know
    

    In Native, it really depends on what sub-target of K/Native you use, so if you add what sub-targets you use (in the comment section), we can figure out an implementation for K/Native.