Kotlin
Summary - Kotlin/Native
Combine interop, memory model and native library to write a native module.
Summary - Kotlin/Native
In this group you learned Kotlin/Native, C interop, the memory model, Konan and native libraries. Now you will write a model that combines them: a Counter and a NativeLib.
Your Counter can be shared in the new memory model; NativeLib represents a native library. In main you will increase the Counter, load the NativeLib, and print them together. This is a typical flow in Kotlin/Native: shared state and a library call.
Combining: shared state + library
Now we will use Counter and NativeLib together. The Counter represents a shared counter in the new memory model; the NativeLib is a native library.
Example: class Counter(private var n: Int = 0) { fun inc() { n += 1 }; fun get(): Int = n } and object NativeLib { val name = "sqlite"; fun load(): String = "loaded: $name" }. In main do val c = Counter(); c.inc() and write println("${'$'}{NativeLib.load()}: ${'$'}{c.get()}"). This is the typical mix of shared state and a library call.
Exercise Write Counter + NativeLib
Define class Counter(private var n: Int = 0); fun inc() should increase n by one; fun get(): Int should return n. Define object NativeLib with val name = "sqlite" and fun load(): String = "loaded: $name". In main, do val c = Counter(); c.inc() and write println("${'$'}{NativeLib.load()}: ${'$'}{c.get()}").
Show example solution
class Counter(private var n: Int = 0) {
fun inc() { n += 1 }
fun get(): Int = n
}
object NativeLib {
val name = "sqlite"
fun load(): String = "loaded: $name"
}
fun main() {
val c = Counter()
c.inc()
println("${NativeLib.load()}:${c.get()}")
}
Test yourself
-
Which action did the new memory model make unnecessary?
- Defining a class
- Loading a library
- Freezing
- Launching a coroutine
Show answer
Freezing — The new model removed the freeze requirement; sharing is free.
-
Complete the load call
object NativeLib {
val name = "sqlite"
fun load(): String = "loaded: ${'$'}____"
}
Show answer
object NativeLib {
val name = "sqlite"
fun load(): String = "loaded: ${'$'}name"
}
-
Match native concepts
- Kotlin/Native
- JVM-less binary
- C interop
- C library binding
- Konan
- Compiler
- framework
- iOS library
Next lesson: KMP