A/B Smartly - Kotlin SDK
The A/B Smartly Kotlin SDK is built with Kotlin 1.9.22 and requires Kotlin 1.9 or later in consuming projects, running on JVM 11+. It uses Jackson for JSON serialization and provides a thread-safe API using ConcurrentHashMap and atomic operations.
The A/B Smartly Kotlin SDK is compatible with Android 5.0 and later (API level 21+).
The android.permission.INTERNET permission is required. To add this permission to your application ensure the following line is present in the AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET"/>To install the ABsmartly Kotlin SDK, place the following in your build.gradle.kts and replace {VERSION} with the latest SDK version available in MavenCentral.
dependencies {
implementation("com.absmartly:absmartly-sdk-kotlin:{VERSION}")
}dependencies {
implementation 'com.absmartly:absmartly-sdk-kotlin:{VERSION}'
}To install the ABsmartly Kotlin SDK, place the following in your pom.xml and replace {VERSION} with the latest SDK version available in MavenCentral.
<dependency>
<groupId>com.absmartly</groupId>
<artifactId>absmartly-sdk-kotlin</artifactId>
<version>{VERSION}</version>
</dependency>Please follow the installation instructions before trying the following code.
This example assumes an Api Key, an Application, and an Environment have been created in the A/B Smartly web console.
import com.absmartly.sdk.*
fun main() {
val sdk = ABsmartly.builder()
.endpoint("https://your-company.absmartly.io/v1")
.apiKey("YOUR_API_KEY")
.application("website")
.environment("production")
.build()
val contextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8")
val context = sdk.createContext(contextConfig)
.waitUntilReady()
val treatment = context.getTreatment("exp_test_experiment")
context.close()
sdk.close()
}import com.absmartly.sdk.*
fun main() {
val clientConfig = ClientConfig.create()
.setEndpoint("https://your-company.absmartly.io/v1")
.setAPIKey("YOUR_API_KEY")
.setApplication("website")
.setEnvironment("production")
val client = Client.create(clientConfig)
val sdkConfig = ABSmartlyConfig.create()
.setClient(client)
val sdk = ABsmartly.create(sdkConfig)
// ...
}If you already have the context data, you can create a context without an additional HTTP request:
val contextData = sdk.getContextData().get()
val contextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8")
val context = sdk.createContextWith(contextConfig, contextData)The createContext() method starts fetching data asynchronously. You can use the context after calling waitUntilReady() or waitUntilReadyAsync():
val context = sdk.createContext(contextConfig)
context.waitUntilReadyAsync().thenAccept { ctx ->
val treatment = ctx.getTreatment("exp_test_experiment")
}If you manage data fetching yourself, pass the data to createContextWith() so the context is still wired to the SDK's publisher and data provider:
val contextData: ContextData = fetchContextData()
val contextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8")
.setPublishDelay(-1)
.setRefreshInterval(0)
val context = sdk.createContextWith(contextConfig, contextData)val sdk = ABsmartly.builder()
.endpoint("https://your-company.absmartly.io/v1")
.apiKey("YOUR_API_KEY")
.application("website")
.environment("production")
.eventLogger(object : ContextEventLogger {
override fun handleEvent(context: Context, type: ContextEventLogger.EventType, data: Any?) {
when (type) {
ContextEventLogger.EventType.Exposure -> {
val exposure = data as Exposure
println("Exposed to experiment: ${exposure.name}")
}
ContextEventLogger.EventType.Goal -> {
val goal = data as GoalAchievement
println("Goal tracked: ${goal.name}")
}
ContextEventLogger.EventType.Error -> {
println("Error: $data")
}
else -> {}
}
}
})
.build()ClientConfig Parameters
| Config | Type | Required? | Description |
|---|---|---|---|
| endpoint | String |
✅ | The A/B Smartly collector endpoint URL (must use https://) |
| apiKey | String |
✅ | Your API key from the A/B Smartly web console |
| application | String |
✅ | The application name as configured in the web console |
| environment | String |
✅ | The environment name as configured in the web console |
| deserializer | ContextDataDeserializer? |
❌ | Custom context data deserializer (defaults to Jackson-based) |
| serializer | ContextEventSerializer? |
❌ | Custom event serializer (defaults to Jackson-based) |
| executor | Executor? |
❌ | Custom executor for async operations |
ContextConfig Parameters
| Method | Description |
|---|---|
setUnit(type, uid) |
Set a unit type and identifier |
setOverride(name, variant) |
Force a specific variant for an experiment |
setCustomAssignment(name, variant) |
Set a custom assignment for an experiment |
setEventLogger(logger) |
Set a context-level event logger |
setPublishDelay(ms) |
Set the publish delay in milliseconds (default: 100) |
setRefreshInterval(ms) |
Set the refresh interval in milliseconds (default: 0) |
val contextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8")
val context = sdk.createContext(contextConfig)
.waitUntilReady()
assert(context.isReady)Creating a context involves obtaining data from the A/B Smartly event collector. You can avoid repeating the round-trip by re-using previously retrieved data:
val contextData = sdk.getContextData().get()
val context = sdk.createContextWith(
ContextConfig.create().setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8"),
contextData
)
val anotherContext = sdk.createContextWith(
ContextConfig.create().setUnit("session_id", "another-session-id"),
contextData
)
assert(anotherContext.isReady)val contextData: ContextData = fetchContextData()
val context = sdk.createContextWith(
ContextConfig.create().setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8"),
contextData
)
assert(context.isReady)For long-running contexts, experiments started after the context was created will not be triggered.
When using the SDK wrapper, call refresh() without arguments to automatically fetch fresh data:
context.refresh().get()When using direct construction, pass the new data explicitly:
val freshData: ContextData = fetchFreshContextData()
context.refresh(freshData)You can add additional units to a context by calling the setUnit() method. This is useful when a user logs in and you want to associate the new identity with the context. Note that you cannot override an already set unit type, as that would be a change of identity and will throw an IllegalArgumentException. In this case, you must create a new context instead.
context.setUnit("db_user_id", "1000013")if (context.getTreatment("exp_test_experiment") == 0) {
// user is in control group (variant 0)
} else {
// user is in treatment group
}val variable = context.getVariableValue("my_variable", "default_value")Variables can be of any type:
val buttonColor = context.getVariableValue("button_color", "blue") as String
val showBanner = context.getVariableValue("show_banner", false) as Boolean
val bannerHeight = context.getVariableValue("banner_height", 200) as IntAlthough generally not recommended, it is sometimes necessary to peek at a treatment or variable without triggering an exposure. The A/B Smartly SDK provides peekTreatment() and peekVariableValue() methods for that.
if (context.peekTreatment("exp_test_experiment") == 0) {
// user is in control group (variant 0)
} else {
// user is in treatment group
}val variable = context.peekVariableValue("my_variable", "default_value")During development, for example, it is useful to force a treatment for an experiment. This can be achieved with the setOverride() method. The setOverride() method can be called before the context is ready.
context.setOverride("exp_test_experiment", 1)The setAttribute() method can be called before the context is ready.
context.setAttribute("user_agent", "Mozilla/5.0...")
context.setAttribute("customer_age", "new_customer")The configured application and environment names are always available to audience filters and
assignment-rule conditions, even when you set no attributes. A user attribute of the same name overrides
the configured value, including one set after an assignment was cached. These values are added only to the
local evaluation map; the collector already attaches them to every exposure server-side, so nothing extra
is published.
ContextConfig.setIncludeSystemAttributes(true) prepends sdk_name and sdk_version to the attributes of every
publish. It is off by default, and neither is published when you set an attribute of the same name. It does not
publish application or environment, and the SDK never adds app_version: to target app versions, set it yourself
with context.setAttribute("app_version", ...).
val clientConfig = ClientConfig.create()
// ...endpoint, API key, application, environment
.setApplicationVersion("2.4.1")
val contextConfig = ContextConfig.create()
.setUnit("session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8")
.setIncludeSystemAttributes(true)The X-Application-Version header carries the version (from ClientConfig.setApplicationVersion, trimmed) only when
it is a whole number of up to 18 digits; otherwise it is "0". The
X-Agent header is absmartly-kotlin-sdk/<version> and is sent on both fetch and publish.
An experiment can carry assignment rules, configured in the web console. The first matching rule assigns the unit,
ahead of the audience, traffic allocation and custom assignments (an override still wins). An assign rule sets a
fixed variant; a split rule randomises the unit over its own percentages with the experiment's seed. Rule-assigned
exposures are flagged ruleOverride so they are excluded from analysis.
Rule conditions are evaluated against the same attributes as audiences and support the semver_eq, semver_gt,
semver_gte, semver_lt and semver_lte operators, so rules (and audiences) can target app versions:
context.setAttribute("app_version", "2.4.1")context.setCustomAssignment("exp_test_experiment", 1)val fieldValue = context.getCustomFieldValue("exp_test_experiment", "my_field")
val fieldType = context.getCustomFieldValueType("exp_test_experiment", "my_field")
val fieldKeys: Set<String> = context.customFieldKeysCustom field values are automatically converted based on their type:
jsontype fields are deserialized into their native typesbooleantype fields returnBooleannumbertype fields returnDouble- Other types return
String
val keys: Map<String, List<String>> = context.variableKeys
// Maps variable names to the list of experiments that define themGoals are created in the A/B Smartly web console.
context.track("payment", mapOf(
"item_count" to 1,
"total_amount" to 1999.99,
))Track a goal without properties:
context.track("page_view", null)Sometimes it is necessary to ensure all events have been published to the A/B Smartly collector, before proceeding. You can explicitly call the publish() method.
context.publish().get()publish() returns a CompletableFuture<Void>; wait on it (get()/join()) or chain on it before relying on the events having been sent.
The close() method will ensure all events have been published to the A/B Smartly collector, like publish(), and will also "seal" the context, throwing an IllegalStateException if any method that could generate an event is called.
context.close()Read methods (getTreatment, peekTreatment, getVariableValue, peekVariableValue, variableKeys, customFieldKeys, getCustomFieldValue, getCustomFieldValueType) throw an IllegalStateException when the context is not ready ("ABsmartly Context is not yet ready.") or when it is closing/closed ("ABsmartly Context is finalizing." / "ABsmartly Context is finalized."). experiments only requires the context to be ready and stays available after close. Overrides and custom assignments (single and bulk setters) also remain allowed after close; treatment reads remain guarded. This matches the JavaScript SDK.
Migration: earlier builds of this branch returned defaults (0, the default value, empty collections or null) in these states. Call waitUntilReady() (or check isReady) before reading, do not read after close(), and catch IllegalStateException where a fallback is needed.
context.isReady // true when context has been initialized with data
context.isFailed // true when context initialization failed
context.isClosed // true when context has been closed
context.pendingCount // number of pending events awaiting publish
context.experiments // list of experiment names in the contextThe A/B Smartly SDK can be instantiated with an event logger. Implement the ContextEventLogger interface to receive SDK lifecycle events.
class CustomEventLogger : ContextEventLogger {
override fun handleEvent(context: Context, type: ContextEventLogger.EventType, data: Any?) {
when (type) {
ContextEventLogger.EventType.Exposure -> {
val exposure = data as Exposure
println("Exposed to experiment: ${exposure.name}")
}
ContextEventLogger.EventType.Goal -> {
val goal = data as GoalAchievement
println("Goal tracked: ${goal.name}")
}
ContextEventLogger.EventType.Error -> {
println("Error: $data")
}
ContextEventLogger.EventType.Publish -> {
val event = data as PublishEvent
println("Published ${event.exposures?.size ?: 0} exposures")
}
ContextEventLogger.EventType.Ready,
ContextEventLogger.EventType.Refresh,
ContextEventLogger.EventType.Close -> {}
}
}
}Usage:
val context = sdk.createContextWith(
ContextConfig.create()
.setUnit("session_id", "abc123")
.setEventLogger(CustomEventLogger()),
contextData
)Event Types
| Event | When | Data |
|---|---|---|
Error |
Context receives an error |
Throwable object |
Ready |
Context turns ready |
ContextData used to initialize |
Refresh |
Context.refresh() method succeeds |
ContextData used to refresh |
Publish |
Context.publish() method succeeds |
PublishEvent sent to collector |
Exposure |
Context.getTreatment() succeeds on first exposure |
Exposure enqueued for publishing |
Goal |
Context.track() method succeeds |
GoalAchievement enqueued for publishing |
Close |
Context.close() method succeeds the first time |
null |
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.absmartly.sdk.*
class MainActivity : AppCompatActivity() {
private lateinit var context: Context
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val sdk = getABsmartly() // your app-wide ABsmartly instance
val contextData = fetchContextData()
val deviceId = getDeviceId()
context = sdk.createContextWith(
ContextConfig.create().setUnit("device_id", deviceId),
contextData
)
val treatment = context.getTreatment("exp_button_color")
if (treatment == 0) {
setContentView(R.layout.activity_main_control)
} else {
setContentView(R.layout.activity_main_treatment)
}
}
override fun onDestroy() {
super.onDestroy()
if (::context.isInitialized) {
context.close()
}
}
}import com.absmartly.sdk.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.sessions.*
fun Application.configureRouting(sdk: ABsmartly, contextData: ContextData) {
routing {
get("/product") {
val sessionId = call.sessions.get<UserSession>()?.id ?: "anonymous"
val context = sdk.createContextWith(
ContextConfig.create().setUnit("session_id", sessionId),
contextData
)
val treatment = context.getTreatment("exp_product_layout")
call.respond(mapOf("treatment" to treatment))
context.close()
}
}
}A/B Smartly is the leading provider of state-of-the-art, on-premises, full-stack experimentation platforms for engineering and product teams that want to confidently deploy features as fast as they can develop them. A/B Smartly's real-time analytics helps engineering and product teams ensure that new features will improve the customer experience without breaking or degrading performance and/or business metrics.