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
相关产品推荐
相关产品推荐

