Ankit Kumar
10/17/2023, 5:43 AMvalue
class
As per my understanding it's helpful to make code more readable as many times using type as Int, String
doesn't explain much about the context
so wrapping the types in value class makes it more readable
Also should we prefer typealias for these cases or value class is fineCLOVIS
10/17/2023, 8:17 AMtypealias EitherFlow<E, T> = Flow<Either<E, T>>
Here, an EitherFlow<…>
and a Flow<Either<…>>
are the same thing. When one appears in the code, it's the same as if you wrote the other.
Value classes create a new type, that isn't the same as the wrapped value.
value class Password(val value: String) {
// you can use the constructor to refuse invalid values
init {
require(value.length > 8) { "Password too short" }
}
// you can override how it is displayed (to ensure passwords don't appear in log files)
override fun toString() = "[***]"
}
Here, a String
and a Password
aren't the same thing. You cannot assign a string to a password:
val a = "test"
val b: Password = a // doesn't compile
but you can ask the class to convert itself (and it may refuse by throwing an exception):
val a = "test"
val b: Password = Password(a) // ok, but may fail
Summary:
• use type aliases when you're giving a new name to an existing type, which makes no difference to the type itself or how it's used
• use value classes when you want to add things to an existing type to make it into something different
(also, this question should have been in #getting-started, not in #kotlin-native)Edoardo Luppi
10/17/2023, 9:42 AMCLOVIS
10/17/2023, 9:44 AMEdoardo Luppi
10/17/2023, 9:45 AMCLOVIS
10/17/2023, 9:47 AMEdoardo Luppi
10/17/2023, 9:48 AMCLOVIS
10/17/2023, 9:51 AMrusshwolf
10/17/2023, 12:18 PMCLOVIS
10/17/2023, 12:44 PM