Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 104 ยท Getting Started

Kotlin on Android - KTX, Java Interop and Parcelize

Learn Android KTX extensions, Kotlin vs Java on Android, @JvmStatic, @JvmOverloads, @JvmField, @JvmName, @Throws, nullability annotations, Java interop and @Parcelize.

Android has been Kotlin-first since 2019: new APIs, samples and documentation come in Kotlin, and Jetpack Compose cannot be written in anything else. Yet Android itself is old, the platform is written in Java, and millions of lines of Java still live in libraries, tutorials and company code bases. Day to day you therefore stand on a boundary: Kotlin code calling a Java framework, sometimes Java code calling your Kotlin, and an annotation or two telling the compiler how the two should see each other.

This lesson collects those boundary tools in one place: Android KTX (Kotlin extensions that make the platform nicer), the real differences between Kotlin and Java on Android, the JVM annotations that control how Kotlin compiles for Java callers, nullability annotations, calling in both directions, and @Parcelize for passing objects between components. Android classes cannot run here, so the Android snippets are read-only. But Kotlin itself runs on the JVM, so the TryIts in this lesson are real: the first one really inspects the Java signatures the Kotlin compiler produced.

Kotlin or Java on Android

Kotlin Java
Null safety In the type system (String vs String?) Convention and annotations
Boilerplate data class, properties, default arguments Getters, setters, builders, overloads
Async code Coroutines and Flow Callbacks, Executor, RxJava
Compose Required Not possible
Official docs and samples Kotlin first Reduced
Interop Calls Java freely Calls Kotlin with some rough edges

You do not have to choose one for a whole project. Both compile to the same JVM bytecode (then to DEX, see Gradle) and live in the same module, so you can convert a file at a time. New code in Kotlin is the sensible default. The rest of this lesson is about making the two halves cooperate.

Android KTX

KTX is a set of extension functions and properties that wrap Java-style Android APIs in idiomatic Kotlin. Nothing new happens at runtime; the extension is an inline helper that calls the original API. The core library is androidx.core:core-ktx, and there are KTX additions for lifecycle, activity, fragment, collection, navigation and more (in some recent releases the -ktx artifacts were merged into the main artifacts, so check the release notes of each library).

Kotlin
// read-only example: before and after KTX
// Without KTX
val editor = prefs.edit()
editor.putString("theme", "dark")
editor.putInt("launches", 3)
editor.apply()

// With KTX (androidx.core.content.edit)
prefs.edit {
    putString("theme", "dark")
    putInt("launches", 3)
}                                   // apply() is called for you

val uri = "https://example.com".toUri()                        // androidx.core.net
val args = bundleOf("id" to 42L, "title" to "Hello")           // androidx.core.os
val values = contentValuesOf("name" to "Ada", "age" to 36)      // androidx.core.content
val alarm = context.getSystemService<AlarmManager>()            // reified type, no cast
view.isVisible = false                                          // androidx.core.view, instead of View.GONE
view.doOnLayout { /* the view has been measured */ }

Other pieces you will use constantly are by viewModels() and by activityViewModels() for ViewModels, lifecycleScope and repeatOnLifecycle for Flow collection, and buildSpannedString { bold { append("Hi") } } for styled text in the View system. Since most KTX code is "just extension functions", you can write your own in the same style whenever an API feels clumsy.

The first stand-in is a plain-Kotlin model of three KTX helpers over fake Java-style classes, so you can see how little magic there is.

Kotlin How KTX helpers work (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

JVM annotations: shaping the Java view of your Kotlin

Kotlin has features Java lacks, such as top-level functions, default arguments, properties and companion objects. The compiler maps them to Java in a standard way, and a handful of annotations change that mapping. They matter on Android for three reasons: Java callers, the XML layout inflater (it calls constructors by signature) and reflection-based libraries.

  • @JvmStatic on a function or property in a companion object or object makes a real static method, so Java can call Util.format() instead of Util.Companion.format().
  • @JvmField exposes a property as a public field without a getter and setter. Use it for constants-like values and for fields that a framework reads by name. (A const val is also a static constant.)
  • @JvmOverloads generates one overload per default argument. Custom Views need it: the layout inflater looks for the constructor (Context, AttributeSet).
  • @JvmName changes the name Java sees. It resolves signature clashes after erasure (two functions with List<String> and List<Int> parameters) and renames the file class: @file:JvmName("Strings") instead of StringsKt.
  • @Throws(IOException::class) declares a checked exception. Kotlin has none, but Java code that tries to catch (IOException e) around a call that "cannot throw it" fails to compile unless you add @Throws.
Kotlin
// read-only example: a custom View that XML can inflate
class BadgeView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
) : AppCompatTextView(context, attrs, defStyleAttr)

Because Kotlin runs on the JVM, the next TryIt can show the real result using Java reflection: it declares a class with these annotations and prints the methods and fields a Java caller would see.

Kotlin What Java sees: JVM annotations (real reflection)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Read the output for the evidence: pad appears three times (with 3, 2 and 1 parameters) because of @JvmOverloads; shout shows up as a static method on Formatter, while plain exists only on Formatter$Companion; DEFAULT_WIDTH is a field, but title is a private field with getTitle() and setTitle(), while the @JvmField subtitle is a public field; the two render functions have different JVM names; and save lists the checked exception.

Nullability annotations and platform types

Java has no null types, but Android annotates its API. androidx.annotation.Nullable and NonNull (and the older android.annotation and javax variants) tell Kotlin what to expect.

  • An annotated @NonNull String appears in Kotlin as String, a @Nullable String as String?, and the compiler enforces it.
  • An unannotated Java type becomes a platform type, written String! in IDE hints. Kotlin lets you treat it as nullable or not, and does not check. If it is actually null and you treat it as non-null, you get a NullPointerException at the use site. For example intent.getStringExtra("name") can return null, so write intent.getStringExtra("name") ?: return.
  • In the other direction, Kotlin inserts a parameter null check into every public function with non-null parameters. A Java caller passing null gets an exception immediately (Parameter specified as non-null is null), which is better than a failure far from the cause.
Java
// read-only example (Java): annotate your Java API so Kotlin callers get real types
public @NonNull String title(@Nullable String raw) {
    return raw == null ? "Untitled" : raw.trim();
}

When you write new Java in a mixed project, annotate every public parameter and return value. When you write Kotlin that Java will call, remember that Java will not stop at the type: public API with non-null parameters rejects null at runtime.

Calling Kotlin from Java, and Java from Kotlin

Kotlin calling Java is almost always painless. Getters and setters become properties (view.text = "Hi" calls setText), a Java interface with one method accepts a lambda (view.setOnClickListener { }), and checked exceptions are not checked.

Java calling Kotlin has rough edges to plan for:

  • Top-level functions live in a class named after the file, with Kt appended: Strings.kt becomes StringsKt.shout(...). Rename it with @file:JvmName.
  • Companion object members need Foo.Companion.bar() unless you add @JvmStatic.
  • Default arguments are invisible to Java unless you add @JvmOverloads.
  • suspend functions compile to a method with an extra Continuation parameter, which Java cannot use sensibly. Offer a callback- or CompletableFuture-based wrapper for Java users (for example with kotlinx-coroutines-jdk8's future { }).
  • Properties need getter calls; @JvmField exposes the field itself.
  • Flow and sealed classes are usable from Java but verbose; keep a Java-friendly facade at the boundary if you ship a library.
Java
// read-only example (Java): calling the Kotlin Formatter from the TryIt above
String a = Formatter.shout("hi");                  // @JvmStatic
String b = Formatter.Companion.plain(" x ");       // companion without @JvmStatic
String c = new Formatter().pad("id");              // @JvmOverloads

Parcelize: passing objects between components

Components exchange data in Bundles, and a Bundle can hold primitives, strings and anything Parcelable. A Parcel is a flat, fast binary container used for inter-process communication (IPC) and for saved state. Writing Parcelable by hand means a writeToParcel, a CREATOR and a constructor that reads fields in exactly the same order. The Parcelize compiler plugin writes that for you.

Kotlin
// read-only example
// plugins { id("org.jetbrains.kotlin.plugin.parcelize") }

@Parcelize
data class Contact(
    val id: Long,
    val name: String,
    val tags: List<String> = emptyList(),
    val kind: Kind = Kind.PERSON,
) : Parcelable {
    enum class Kind { PERSON, COMPANY }
}

// Passing it with an intent, and getting it back (API 33+ typed overload)
intent.putExtra("contact", contact)
val back = intent.getParcelableExtra("contact", Contact::class.java)

// rememberSaveable can store any Parcelable without a custom Saver
var selected by rememberSaveable { mutableStateOf<Contact?>(null) }

Notes about Parcelize:

  • Only properties declared in the primary constructor are written. Body properties are not.
  • It supports primitives, strings, collections, enums, other Parcelables, Serializable and more; use @TypeParceler for a type it does not know.
  • A Parcel is not for storage. Its format can change between Android versions, so never write bytes to disk or a database.
  • Bundles cross a Binder with a transaction buffer of about 1 MB shared by the whole process. Large objects in intents or saved state cause TransactionTooLargeException; pass an id and reload from a repository.
  • With Navigation Compose type-safe routes, @Serializable is the more common choice for arguments; see JSON and serialization.

The last stand-in does by hand what the plugin generates: a fake Parcel that reads values back in write order, which makes the one hard rule of Parcelable visible.

Kotlin Write order equals read order (Parcel stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

@Parcelize removes this boilerplate and, more importantly, the chance of writing the fields in one order and reading them in another.

Common mistakes

  • Treating a platform type (String!) as non-null without a check. Test or default values from Java APIs such as getStringExtra.
  • Forgetting @JvmOverloads on a custom View constructor. The app crashes with an inflation error because no (Context, AttributeSet) constructor exists.
  • Calling suspend functions from Java and fighting the Continuation parameter instead of exposing a callback or future.
  • Using Parcel data for persistence or putting huge objects in a Bundle.
  • Expecting body properties to be parceled. Only primary-constructor properties are.
  • Writing a second layer of wrappers for things KTX already has. Check the KTX before writing your own helper.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which annotation do you add so a custom View with default constructor arguments can be inflated from XML?

    The inflater looks for a constructor taking (Context, AttributeSet). @JvmOverloads generates all the shorter constructors from the default arguments.
  2. 2. What does an unannotated Java return type look like in Kotlin?

    Platform types let you choose, but the compiler cannot protect you: a null treated as non-null throws at the use site.
  3. 3. Which statement about @Parcelize is correct?

    Only primary-constructor properties are parceled, and a Parcel is for short-lived IPC and saved state, not storage.
  4. 4. A Java file wants to call your Kotlin companion function as Utils.format(x). What do you add?

    Without @JvmStatic Java must write Utils.Companion.format(x). The annotation also generates a real static method.
  5. 5. Why is KTX not a performance concern?

    KTX adds no new runtime machinery. The extensions are thin, mostly inline wrappers over the normal Android APIs.

Summary

  • Android is Kotlin-first, but Java and Kotlin mix freely in one module; new code in Kotlin is the default.
  • Android KTX adds extension functions such as edit { }, bundleOf, toUri and getSystemService<T>() over the Java-style APIs.
  • @JvmStatic, @JvmField, @JvmOverloads, @JvmName and @Throws control what Java callers and the XML inflater see; the reflection TryIt shows the real signatures.
  • Java types without nullability annotations are platform types: Kotlin does not check them, so handle null yourself.
  • Java calling Kotlin has rough edges: Kt file classes, Companion, default arguments and suspend functions.
  • @Parcelize generates Parcelable code for primary-constructor properties; Parcels are for IPC and saved state, not storage, and Bundles must stay small.
  • The Android snippets are read-only; the TryIts model KTX and Parcel and really reflect on JVM signatures.

Next: What Is Android?