You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin多平台如何获取换行符长度?求Native/JS/Desktop实现方案

Kotlin多平台获取换行符长度的跨平台实现

在Kotlin多平台项目中,推荐使用expect/actual机制实现跨平台功能,先在通用模块定义期望函数,再针对不同平台实现具体逻辑:

通用模块(commonMain)

定义跨平台通用的函数声明:

expect fun lineSeparatorLength(): Int

各平台具体实现

JVM平台

你已实现的代码可直接作为actual实现:

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

Native/Desktop平台(Windows、macOS、Linux原生)

方式一:基于POSIX API判断系统

import platform.posix.uname

actual fun lineSeparatorLength(): Int {
    val sysName = uname().sysname
    val lineSeparator = when (sysName) {
        "Darwin", "Linux" -> "\n"
        "Windows_NT" -> "\r\n"
        else -> "\n" // 兜底默认值
    }
    return lineSeparator.length
}

方式二:使用Kotlin Native内置API(Kotlin 1.6+)

如果项目使用Kotlin 1.6及以上版本,可直接调用原生平台提供的换行符工具类:

import kotlin.native.platform.LineSeparator

actual fun lineSeparatorLength(): Int = LineSeparator.current.length

JS平台

兼容浏览器和Node.js两种环境:

actual fun lineSeparatorLength(): Int {
    // 判断是否为Node.js环境
    val hasOsModule = jsTypeOf(js("typeof os !== 'undefined' ? os : null")) != "undefined"
    val lineSeparator = if (hasOsModule) {
        js("os.EOL").toString()
    } else {
        // 浏览器环境根据平台判断
        val isWindows = js("navigator.platform").toString().contains("Win", ignoreCase = true)
        if (isWindows) "\r\n" else "\n"
    }
    return lineSeparator.length
}

内容的提问来源于stack exchange,提问作者user14381362

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 13:31:02