Select spec version:

Use RudderTyper with Kotlin Multiplatform

Generate SDK-free Kotlin bindings from your Tracking Plan for code shared between Android and iOS, and send events through each platform’s RudderStack SDK.
Available Plans
  • free
  • growth
  • enterprise

By default, the Kotlin bindings that rudder-cli typer generate writes include a RudderAnalytics client. That client calls the RudderStack Kotlin SDK, which targets Android and the JVM, so the file doesn’t compile in Kotlin Multiplatform commonMain code or for an iOS target.

--option emit=common writes a file that doesn’t depend on any RudderStack SDK. Your shared code calls the typed client, and each platform forwards the events to its own SDK: the Kotlin SDK on Android and the Swift SDK on iOS.

How the pieces fit

LayerWho writes itWhat it does
RudderTyper and the modelsGeneratedTyped methods for each event in your Tracking Plan, in commonMain
RudderTyperTransportGeneratedA four-method interface (track, identify, group, screen) that RudderTyper calls
Android transportYouImplements RudderTyperTransport on the Kotlin SDK
iOS transportYouImplements the same interface, as a Swift protocol, on the Swift SDK

Prerequisites

  • Install Rudder CLI v1.2.0 or later. Verify with rudder-cli --version.
  • A Kotlin Multiplatform module with kotlinx-serialization-json as a commonMain dependency.
  • The RudderStack Kotlin SDK in your Android module and the RudderStack Swift SDK in your iOS app.
  • Verified with Kotlin SDK 2.2.0 and Swift SDK 2.1.0.
  • A Tracking Plan ID, or a snapshot file of the plan saved with typer snapshot.

Generate the bindings

Generate with --option emit=common into your commonMain source set. The directory has to match the package name:

bash
rudder-cli typer generate \
    --platform kotlin \
    --tracking-plan-id tp_1234567890abcdef \
    --option emit=common \
    --option packageName=com.example.analytics \
    --output shared/src/commonMain/kotlin/com/example/analytics

The file imports kotlinx-serialization-json and kotlin.jvm.JvmName; passing --option composeImmutable=true also adds androidx.compose.runtime.Immutable and requires androidx.compose.runtime on the commonMain classpath. It contains the models (data classes, enums, sealed classes, and their rudderSerialize() functions), RudderTyperTransport, and RudderTyper.

Implement the Android transport

Every transport method ends with a RudderTyperOptions parameter. It has two fields. context is custom context for the event, and it already holds the ruddertyper context, which has the platform, the CLI version, and the Tracking Plan ID and version, next to any custom context the caller passed. integrations turns destinations on or off for the event. Attach both to the SDK’s event options. Because the options are a class, a later release can add a field without breaking the transports you wrote.

The maps hold plain Kotlin values (String, Boolean, Long, Double, Map, List, and null). The Kotlin SDK takes JsonObject values, so this transport converts the maps first. Replace com.example.analytics with your package name:

kotlin
import android.app.Application
import com.example.analytics.RudderTyperOptions
import com.example.analytics.RudderTyperTransport
import com.rudderstack.sdk.kotlin.android.Analytics
import com.rudderstack.sdk.kotlin.android.Configuration
import com.rudderstack.sdk.kotlin.core.internals.logger.Logger
import com.rudderstack.sdk.kotlin.core.internals.models.RudderOption
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive

/** Implements the generated transport on top of the RudderStack Kotlin SDK. */
class AndroidTransport(
    application: Application,
    writeKey: String,
    dataPlaneUrl: String,
    controlPlaneUrl: String = "https://api.rudderlabs.com",
) : RudderTyperTransport {
    private val analytics = Analytics(
        Configuration(
            writeKey = writeKey,
            application = application,
            dataPlaneUrl = dataPlaneUrl,
            controlPlaneUrl = controlPlaneUrl,
            logLevel = Logger.LogLevel.DEBUG,
        )
    )

    override fun track(name: String, properties: Map<String, Any?>, options: RudderTyperOptions) {
        analytics.track(name, properties.toJsonObject(), options.toOption())
    }

    override fun identify(userId: String, traits: Map<String, Any?>, options: RudderTyperOptions) {
        analytics.identify(userId, traits.toJsonObject(), options.toOption())
    }

    override fun group(groupId: String, traits: Map<String, Any?>, options: RudderTyperOptions) {
        analytics.group(groupId, traits.toJsonObject(), options.toOption())
    }

    override fun screen(screenName: String, category: String, properties: Map<String, Any?>, options: RudderTyperOptions) {
        analytics.screen(screenName, category, properties.toJsonObject(), options.toOption())
    }
}

private fun RudderTyperOptions.toOption() =
    RudderOption(integrations = integrations.toJsonObject(), customContext = context.toJsonObject())

private fun Map<String, Any?>.toJsonObject() = JsonObject(mapValues { it.value.toJsonElement() })

private fun Any?.toJsonElement(): JsonElement = when (this) {
    null -> JsonNull
    is JsonElement -> this
    is Boolean -> JsonPrimitive(this)
    is Number -> JsonPrimitive(this)
    is String -> JsonPrimitive(this)
    is Map<*, *> -> JsonObject(entries.associate { (k, v) -> k.toString() to v.toJsonElement() })
    is Iterable<*> -> JsonArray(map { it.toJsonElement() })
    else -> JsonPrimitive(toString())
}

Implement the iOS transport

Add the rudder-sdk-swift package to your iOS app and link the shared module as a framework named Shared. Kotlin exports RudderTyperTransport as a Swift protocol, and the maps arrive as [String: Any].

Convert every Kotlin Boolean to a Swift Bool before you pass the values to the SDK. Swift receives a Kotlin Boolean as KotlinBoolean, which is a subclass of NSNumber, and the Swift SDK encodes an NSNumber as an integer. Without the conversion, true goes out as 1 and false as 0, and the event fails the Tracking Plan’s type check. The plainMap function in the code below does the conversion, including for nested maps and lists.
swift
import Foundation
import RudderStackAnalytics
import Shared

/// Implements the generated Kotlin RudderTyperTransport protocol on top of the RudderStack Swift SDK.
final class IosTransport: NSObject, RudderTyperTransport {
    private let analytics: Analytics

    init(writeKey: String, dataPlaneUrl: String, controlPlaneUrl: String) {
        analytics = Analytics(configuration: Configuration(
            writeKey: writeKey,
            dataPlaneUrl: dataPlaneUrl,
            controlPlaneUrl: controlPlaneUrl,
            logLevel: .debug
        ))
    }

    func track(name: String, properties: [String: Any], options: RudderTyperOptions) {
        analytics.track(name: name, properties: plainMap(properties), options: options.toOption())
    }

    func identify(userId: String, traits: [String: Any], options: RudderTyperOptions) {
        analytics.identify(userId: userId, traits: plainMap(traits), options: options.toOption())
    }

    func group(groupId: String, traits: [String: Any], options: RudderTyperOptions) {
        analytics.group(groupId: groupId, traits: plainMap(traits), options: options.toOption())
    }

    func screen(screenName: String, category: String, properties: [String: Any], options: RudderTyperOptions) {
        analytics.screen(screenName: screenName, category: category, properties: plainMap(properties), options: options.toOption())
    }
}

private extension RudderTyperOptions {
    func toOption() -> RudderOption {
        RudderOption(integrations: plainMap(integrations), customContext: plainMap(context))
    }
}

/// Kotlin Boolean values reach Swift as KotlinBoolean, an NSNumber. The Swift SDK encodes an NSNumber
/// as an integer, so a Kotlin `true` would go out as 1. Unwrap them to Swift Bool, recursively.
private func plainMap(_ map: [String: Any]) -> [String: Any] {
    map.mapValues(plainValue)
}

private func plainValue(_ value: Any) -> Any {
    if let boolean = value as? KotlinBoolean { return boolean.boolValue }
    if let map = value as? [String: Any] { return plainMap(map) }
    if let list = value as? [Any] { return list.map(plainValue) }
    return value
}

Create the transport in each app and pass it to your shared code, for example through the entry point of a Compose Multiplatform screen.

Send events from shared code

Create RudderTyper once with the transport and call the typed methods:

kotlin
val typer = RudderTyper(transport)

typer.trackProductClicked(TrackProductClickedProperties(productId = "p_123"))

Every typed method also takes an optional options argument for custom context and integrations:

kotlin
typer.trackProductClicked(
    TrackProductClickedProperties(productId = "p_123"),
    RudderTyperOptions(integrations = mapOf("All" to true, "Amplitude" to false)),
)

The method and class names follow your Tracking Plan. For an event named Product Clicked, the method is trackProductClicked, and its properties class is TrackProductClickedProperties. See Naming conventions for the rules.

Switch between workspaces

The Tracking Plan ID and version differ for each workspace, for example production and staging, while the event models stay the same. RudderTyper takes the ID and version as constructor arguments, and uses the generated values by default:

kotlin
val typer = RudderTyper(
    transport,
    trackingPlanId = "tp_staging_plan",
    trackingPlanVersion = 9,
)

Choose the pair at runtime, the same way you choose the data plane URL and write key. Swift callers must pass the Tracking Plan ID and version explicitly because Kotlin default arguments aren’t exposed to Swift. The models only match if both workspaces have the same event shapes at the versions you choose.

The version has to exist for that plan. RudderStack validates an event against the Tracking Plan version it names, and drops an event that names a version the plan doesn’t have, without reporting a violation.

Differences from the default output

  • RudderTyper methods take options: RudderTyperOptions where RudderAnalytics methods take the SDK’s RudderOption. It carries custom context and integrations, which are the parts of RudderOption that the typed client uses.
  • identify and group always send traits through the traits argument of the transport, whichever identity section the rule uses.
  • The generated file imports kotlin.jvm.JvmName, because common code has no implicit kotlin.jvm imports.

Troubleshooting

ErrorCause and fix
Unresolved reference to com.rudderstack.sdk or JvmName in commonMainThe file was generated without --option emit=common. The default output depends on the Kotlin SDK and doesn’t compile in common code. Generate it again with the option.
invalid emit value "<value>": must be "all" or "common"Use --option emit=all or --option emit=common.
unknown option 'emit' for platform '<platform>'emit exists only for the kotlin platform.
unknown option 'emit' for platform 'kotlin'Your Rudder CLI is older than v1.2.0. Upgrade it.
Boolean properties arrive as 1 and 0 from iOSThe iOS transport passes KotlinBoolean values to the Swift SDK. Convert them to Bool as shown in Implement the iOS transport.

See more

Questions? Let's figure it out together.

Join the RudderStack Slack community to connect with other users, customers, and the RudderStack team — or reach out for direct support.