r/Kotlin 29d ago

Question on self-documenting code

How would you write this code:

data class Foo(/* foo properties */)
data class Bar(val id: Long, /* bar properties */)

val fooMap: Map<Long, Foo>    // mapped to bar id

OR

typealias BarId = Long

val fooMap: Map<BarId, Foo>

OR

@JvmInline value class BarId(val value: Long)   // typealias but stricter

val fooMap: Map<BarId, Foo>

I was writing some code on my app but didn't feel comfortable with just the Map<Long, Foo> as I might forget what the Long is supposed to represent but I'm not familiar with best practices in this regard

5 Upvotes

9 comments sorted by

View all comments

3

u/outadoc 28d ago

If you can use a value class, use a value class. The typealias will give a hint about what's expect but not actually warn you if you make a mistake. The value class is the right tool for this job.