I have this code:
In commonMain :
expect class ReadWriteFile
In androidMain :
actual class ReadWriteFile {
fun read(path : String, filename: String) : Boolean {
val file = File("$path/$filename")
return if(file.exists()) {
file.forEachLine {
// do something
}
true
} else {
false
}
}
fun save(path : String, filename : String, nbLine : Int) {
val file = File("$path/$filename")
val w = file.writer()
for(it in 1..nbLine) {
w.write("write something\n")
}
w.close()
}
}
In iosMain :
actual class ReadWriteFile {
fun read(path : String, filename: String) : Boolean {
???????????
}
fun save(path : String, filename : String, nbLine : Int) {
???????????
}
}
The Kotlin/Native compiler can produce a framework for macOS and iOS out of the Kotlin code. The created framework contains all declarations and binaries needed to use it with Objective-C and Swift. The best way to understand the techniques is to try it for ourselves.
With Kotlin Multiplatform, you can create different multiplatform projects for multiple platforms, including web, desktop, and other native platforms. Kotlin applications will work on different operating systems, such as macOS, Windows, Linux, Android, iOS, watchOS, and others.
Android and iOS applications With Kotlin Multiplatform Mobile, you can build cross-platform mobile applications and share common code between Android and iOS, such as business logic, connectivity, and more.
Programming languages such as Swift and Objective C for iOS, and Java and Kotlin for Android, are used to create native applications and programming platforms such as Xamarin and React Native are used for developing hybrid applications.
Try something like this:
import platform.Foundation.*
class ReadWriteFile {
fun read(path : String, filename: String) : Boolean {
val string = NSString.stringWithContentsOfFile(path, NSUTF8StringEncoding, null) ?: return false
string.lines().forEach {
println(it)
}
return true
}
fun save(path : String, filename : String, nbLine : Int) {
val result = (1..nbLine).map {
"string $it"
}
(result as NSString).writeToFile(path, true, NSUTF8StringEncoding, null)
}
}
In general, if you need to find a native solution, its easier to search for an Obj-C one - as kotlin gets converted to it, not Swift, then import platform.Foundation.*
or import platform.UIKit.*
depending on used classes and adopt to kotlin.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With