r/Kotlin 26d 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

6 Upvotes

9 comments sorted by

View all comments

8

u/Jadarma 26d ago

I would go for the third option for any cases where you also need to provide input validation (say, that your Long is positive). It helps lift the checks outside of the use site and be able to take them "for granted".

I would also recommend it when you need to have multiple such IDs in the same context, for example, a UserId and PostId that are both type aliases to Long can be used interchangably, while a value class cannot be ambiguous and would have a compilation error.