https://kotlinlang.org logo
#android
Title
# android
e

Erlan Amanatov

12/13/2023, 1:23 PM
Hi, in some MVI projects I've encountered the use of value class
Copy code
sealed interface Event
@JvmInline
value class SomeEvent(val value: String): Event
What are the advantages and disadvantages of this approach compared to a data classes?
data class SomeEvent(val value: String): Event
s

Shahzad Ansari

12/13/2023, 1:34 PM
From performance perspective, they are more performant as compared to regular classes as they are just wrappers around some value. The difference is that you can only have a single property in a value class which is not the case with data classes. @Dave Leeds probably defines it best https://typealias.com/guides/introduction-to-inline-classes/
e

Erlan Amanatov

12/13/2023, 1:37 PM
I thought there might be some pitfalls when using value classes
m

mkrussel

12/13/2023, 2:57 PM
Value classes have interop issues with Java and Objective-C.
a

Albert Chang

12/13/2023, 3:55 PM
In this case, if you use the
Event
interface instead of the
SomeEvent
as parameter type or return type, the value won't be actually inlined. So unless you use
SomeEvent
type everywhere (which is likely impossible), there aren't really any advantages of using value class.
1
a

agrosner

12/13/2023, 10:28 PM
In an mvi app, the performance benefits are so negligible that it’s not really worth it in my opinion. It’ll attempt to inline the value where it’s used vs boxing it (just like the primitive boxed types). If you use it in a when statement, it’ll (likely) end up boxing it since it needs a way to know the type instance. These are certainly useful for enforcing zero overhead type safe apis that wrap values like Email or Password types. Typealiases don’t do enforcement that these types provide.