CodeGym /Courses /Kotlin SELF /typealias and value class: readability and type safety

typealias and value class: readability and type safety

Kotlin SELF
Level 33, Lesson 4
Available

1. Introduction

If you are writing a small program, it seems normal that you have String, Int, Long everywhere. But as soon as you have even a mini project (for example, our console expense tracker), a weird reality surfaces: the same data type can represent completely different entities.

For example, Int can be both an “expense ID”, a “number of days”, and a “discount percent”. And String can be a “category name”, an “email”, or a “CLI command”. The compiler does not care: it sees just Int and just String. And that is where the classic starts: “oops, I passed the wrong thing, but it compiled.”

Our goal today is to give words in code normal names. Sometimes it is just for readability, and sometimes it is so the compiler becomes our strict friend who does not let nonsense through.

2. typealias: a nice name without a new type

When you read a function signature like fun addExpense(id: Int, amount: Long, category: String), your brain pauses: “And what is Int here? How many? An ID? The cat’s age?” And it is not your fault—this is how primitive types work: they do not carry meaning.

typealias solves exactly the readability problem. It lets you declare an alias for an existing type: essentially, you say “let String in this place be called CategoryName”. But it is important: this is not a new type, just a different name.

Mini example of typealias in our project

Let’s imagine that in our “Expense Tracker” app an expense has:

  • id (for now Int)
  • category (for now String)

Let’s make the code a bit more “human-friendly”:

typealias ExpenseId = Int
typealias CategoryName = String

data class Expense(
    val id: ExpenseId,
    val title: String,
    val category: CategoryName,
    val amountCents: Long,
)

Now function signatures look nicer:

typealias ExpenseId = Int

fun removeExpenseById(expenses: MutableList<Expense>, id: ExpenseId): Boolean {
    val index = expenses.indexOfFirst { it.id == id }
    if (index == -1) return false

    expenses.removeAt(index)
    return true
}

It looks cleaner: it is immediately clear that the parameter is specifically an expense identifier.

The main catch with typealias

A critically important fact: typealias is assignment-compatible with the original type and with other aliases of the same underlying type. Kotlin explicitly emphasizes the difference: typealias is just an alternative name for an existing type, not a new type.

That means code like this… will compile:

typealias UserId = String
typealias ProductId = String

fun printUser(id: UserId) {
    println("user=$id")
}

fun main() {
    val product: ProductId = "P-10"
    printUser(product) // compiles because both are String
}

From Kotlin’s point of view, it is like “well, sure, a String is a String”. But from a meaning point of view, we just fed a function that expects a “user ID” with a product identifier. It is like labeling a package “coffee” and putting screws inside: technically it is a box, but expectations suffered.

When typealias is good

After that catch, it is easy to want to say: “So why is it needed at all?” It is needed—and often.

typealias works great when:

  • you need function signatures to be readable (especially in utilities/services);
  • “mixing up values” is either unlikely or not critical;
  • you do not want to complicate the code with wrappers and .value.

For example, for a “category name” (CategoryName), the “mixed it up with another String” error is possible, but often you still have to validate it with logic anyway (empty string, whitespace, case normalization). There, type safety does not always pay off.

Another common scenario is long functional types (we covered them earlier), where typealias turns “arrow spaghetti” into a normal word. But in today’s lecture we stay closer to domain values.

3. value class: a separate type on top of a single value

Now for the “heavy artillery”. If typealias is “rename the sign on the door”, then value class is “build a separate room”. It looks similar: in both cases, you want to “mark the meaning”. But the result is fundamentally different.

value class creates a real new type that the compiler distinguishes from the underlying type and from other value classes built on top of the same underlying type. That is exactly what gives us protection from accidental substitutions.

Kotlin describes such classes as inline value classes: they store one value, and that value is “inlined” into usage (without a separate “fat object” in most cases).

On Kotlin/JVM (and we are on the JVM here), value class is typically written with the annotation @JvmInline.

Example: ExpenseId as a value class

Let’s make an expense identifier a real separate type:

@JvmInline
value class ExpenseId(val value: Int)

And now the model:

data class Expense(
    val id: ExpenseId,
    val title: String,
    val category: String,
    val amountCents: Long,
)

What this gives in practice

Now the compiler will not let you mix up ExpenseId and “just a number”:

@JvmInline
value class ExpenseId(val value: Int)

fun removeExpenseById(expenses: MutableList<Expense>, id: ExpenseId): Boolean = true

fun main() {
    val id = ExpenseId(10)
    // removeExpenseById(mutableListOf(), 10) // does not compile
    removeExpenseById(mutableListOf(), id)    // ok
}

So a “meaning error” becomes a “compile-time error”. That is the ideal outcome: you catch the issue before the program runs, before tests, before a user writes to you “everything is broken”.

4. Limitations and rules of value class

value classes have limitations. Not because Kotlin is being picky, but because this construct must remain “lightweight” and predictable.

Exactly one field in the primary constructor

An inline value class must have exactly one property initialized in the primary constructor.

So this is allowed:

@JvmInline
value class Money(val cents: Long)

But this is not:

@JvmInline
value class Money(val cents: Long, val currency: String) // error: two fields

If you need two fields, that is already a candidate for a data class, not a value class.

You can have init and check invariants

A very nice advantage: a value class can have an init, and you can protect the meaning of the type right away. And the checks themselves are convenient to do via require(...), which we already used in constructors and init blocks of regular classes.

For example, “money must not be negative”:

@JvmInline
value class Money(val cents: Long) {
    init {
        require(cents >= 0) { "Money must be non-negative: $cents" }
    }
}

This turns an “agreement in your head” into a “rule in code”. And that is great: you can spend brainpower on tasks, not on keeping a hundred agreements in mind.

Why === does not make sense for a value class

Inline value classes can be represented as a “pure value” or as a “wrapper” in some cases. That is why referential equality (===) is forbidden for them as meaningless.

Practically, the takeaway for us is simple: compare value classes as values, using ==.

@JvmInline
value class ExpenseId(val value: Int)

fun main() {
    val a = ExpenseId(1)
    val b = ExpenseId(1)

    println(a == b) // true
}

5. Integrating value class into the “Expense Tracker” project

Now we will take a very practical step: strengthen the model so it allows fewer meaningless states.

Creating domain types: ExpenseId and Money

@JvmInline
value class ExpenseId(val value: Int)

@JvmInline
value class Money(val cents: Long) {
    init {
        require(cents >= 0) { "Money must be non-negative: $cents" }
    }
}

Updating the Expense model

Note: we make money a Money type, but we will keep category as a string (or a typealias) for now, because a category is more of a “text label”, while money and IDs are especially easy to mix up.

typealias CategoryName = String

data class Expense(
    val id: ExpenseId,
    val title: String,
    val category: CategoryName,
    val amount: Money,
)

Adding a small ID generator

For now, without “complex storage” and without topics from future days—let’s just carefully create the next ID based on current expenses.

fun nextExpenseId(expenses: List<Expense>): ExpenseId {
    val max = expenses.maxOfOrNull { it.id.value } ?: 0
    return ExpenseId(max + 1)
}

Yes, this is not ideal for concurrency, databases, and the real world. But for a learning console app it is great. And most importantly: it is clear where exactly we cross over into the “raw number” (.value).

Expense adding function

fun addExpense(
    expenses: MutableList<Expense>,
    title: String,
    category: CategoryName,
    amountCents: Long,
) {
    val expense = Expense(
        id = nextExpenseId(expenses),
        title = title,
        category = category,
        amount = Money(amountCents),
    )
    expenses.add(expense)
}

Notice a nice effect: the Money(amountCents) constructor validates the input by itself. If you try to pass -10, the program will fail immediately and honestly, rather than creating an “expense minus 10 cents” (which later breaks reports and triggers the philosophical question: “did they pay me extra for buying bread?”).

Printing an expense

fun printExpense(e: Expense) {
    println("#${e.id.value}: ${e.title}")                     // #1: Coffee
    println("Category: ${e.category}")                         // Category: food
    println("Amount: ${e.amount.cents} cents")                 // Amount: 250 cents
}

Here .value / .cents is the cost of type safety. Often that is perfectly fine: you explicitly see the boundary between “our semantic type” and a “raw primitive”.

6. typealias vs value class: a selection table

When tools look similar externally, a beginner’s brain starts to panic: “what should I choose so I won’t be embarrassed?” Let’s remove the anxiety with a simple comparison.

Criterion typealias value class
Creates a new type? No, it is an alias of an existing type. Yes, it is a separate type on top of a single value.
Protects from mixing up UserId and ProductId? No Yes
Requires .value / .cents? No Yes (usually yes, because there is a wrapper)
Can you validate meaning in init? No (it is not a class) Yes, you can: init { require(...) }
“One field” limitation Not applicable Yes, one field in the primary constructor
Referential equality === Possible (if the underlying type is a reference type), but almost never needed Meaningless and forbidden

And a very practical everyday rule: if you just want to read the code without decoding, choose typealias. If you want the compiler to slap your hands for confusion, choose value class.

7. API nuance: do not turn code into a “wrapper museum”

There is a temptation to wrap absolutely everything in a value class: Title, CategoryName, Command, Email, CityName… and suddenly your code starts looking like a wrapper museum, where you cannot just pass a string without three rituals.

Psychologically, it is an understandable temptation: “if it is type-safe, it must be better”. But in practice, type safety must pay for its “ceremonial overhead”.

In our app, what is truly risky is:

  • IDs (they are easy to mix up and hard to notice the mistake),
  • money/amounts (a unit mistake or a “minus” sign often breaks calculations).

But “category” most often still requires normalization (trim, lowercase) and allows free-form user input. So there, typealias is often enough, and type safety is achieved not by types but by string validation.

8. Common mistakes

Mistake #1: expecting typealias to protect you from mixing up values.
typealias makes code more readable, but it does not create a new type: everything remains compatible with the underlying type, and the compiler will not stop you if you pass the “wrong String”. If you need actual protection, use a value class.

Mistake #2: trying to make a value class with two (or zero) fields.
An inline value class must have exactly one field in the primary constructor. If you need more data, that is no longer a value class, but a candidate for a data class.

Mistake #3: forgetting that a value class is a new type and being surprised “why it doesn’t compile”.
After switching from Int to ExpenseId, you can no longer call functions with “old numbers”. That is not a bug; it is the whole point: the compiler now requires explicit construction of ExpenseId(…), so you consciously say “this is an ID”.

Mistake #4: not validating meaning even though the type practically asks for it.
If you introduce Money but allow negative values, you lose half the benefit. init { require(...) } is a great way to bake an invariant directly into the type.

Mistake #5: trying to use === with a value class.
Referential equality for inline value classes is meaningless and forbidden, because such values can be represented differently (as a value or as a wrapper). Use == for comparison, and in most cases that is exactly what you need semantically.

Mistake #6: wrapping everything and making the API inconvenient.
If you wrap every string and every number in a value class, you will end up with lots of noisy conversions and .value. Type safety should be precise: protect the places where an error is actually likely and expensive (IDs, money, keys, tokens), and do not turn the whole codebase into a packaging workshop.

1
Task
Kotlin SELF, level 33, lesson 4
Locked
Category label
Category label
1
Task
Kotlin SELF, level 33, lesson 4
Locked
Alias trap
Alias trap
1
Task
Kotlin SELF, level 33, lesson 4
Locked
Money without a minus
Money without a minus
1
Task
Kotlin SELF, level 33, lesson 4
Locked
Pass matching a pattern
Pass matching a pattern
1
Survey/quiz
`data class` and `value class`, level 33, lesson 4
Unavailable
`data class` and `value class`
`data class` and `value class`
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION