CodeBlanks Logo Icon CodeBlanks

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.

Practice 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()}").

Starter code

Main.kt
// add the Counter and NativeLib definitions

fun main() {
    // increase Counter, load NativeLib, and print
}

Sample solution

Main.kt
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()}")
}

Expected output

loaded: sqlite: 1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which action did the new memory model make unnecessary?

  • Defining a class
  • Loading a library
  • Freezing Correct answer
  • Launching a coroutine

Explanation: The new model removed the freeze requirement; sharing is free.

2 Complete the load call

Question
object NativeLib {
    val name = "sqlite"
    fun load(): String = "loaded: ${'$'}____"
}
Answer
object NativeLib {
    val name = "sqlite"
    fun load(): String = "loaded: ${'$'}name"
}

Explanation: ${'$'}name embeds the library name into the string.

3 Match native concepts

Term Meaning
Kotlin/Native JVM-less binary
C interop C library binding
Konan Compiler
framework iOS library

All lessons in Expert