UserDefault and SharedPreference in Kotlin Multiplatform Mobile (KMM)

Create a KMM Project

In android studio install KMM plugin and than using that create a KMM project. for details you can read my blog explaining how to create Hello Wolrd app in KMM

Shared Code

This module contains commonMain, androidMain and iosMain. In commonMain we will write the expect signatures of the functions which are responsible to interact with SharedPreference and UserDefaults.

expect class SPref

expect fun SPref.getInt(key: String) : Int
expect fun SPref.setInt(key: String, value: Int)
import android.content.Context.MODE_PRIVATE
import android.content.SharedPreferences

actual typealias SPref = Activity

actual fun SPref.getInt(key: String ) : Int{
val prefs: SharedPreferences = this.getSharedPreferences("", MODE_PRIVATE)
return prefs.getInt(key, -1)

actual fun SPref.setInt(key: String, value: Int) {
val prefs: SharedPreferences = this.getSharedPreferences("", MODE_PRIVATE)
val editor = prefs.edit()
import platform.Foundation.NSUserDefaults
import platform.darwin.NSObject

actual typealias SPref = NSObject

actual fun SPref.getInt(key: String) : Int {
return NSUserDefaults.standardUserDefaults.integerForKey(key).toInt()

actual fun SPref.setInt(key: String, value : Int){
class KMMStorage(val context: SPref) {

fun getInt(key: String): Int {
return context.getInt(key)

fun putInt(key: String, value: Int) {

Android Main Activity

class MainActivity : AppCompatActivity() {

lateinit var tv : TextView

override fun onCreate(savedInstanceState: Bundle?) {

tv = findViewById(

fun loadFromSP(view : View) {
var kmmStorage = KMMStorage(this)
var count = kmmStorage.getInt("count")
tv.text = "Current Count is "+count
kmmStorage.putInt("count", count)


iOS ContentView

import SwiftUI
import Foundation
import shared

func getCount() -> Int32 {
let kmmStorage = KMMStorage(context : NSObject())
var count = kmmStorage.getInt(key : "count")
kmmStorage.putInt(key: "count", value: count)
return count

struct ContentView: View {
@State var counter: Int32 = 0
var body: some View {
VStack(spacing: 50) {
Button(action: {
counter = getCount()
}) {
Text("Get Data from User Default")

struct ContentView_Previews: PreviewProvider {
static var previews: some View {


Source Code

full project can be downloaded from github



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store