Orhan Tozan
09/27/2021, 1:41 PMvalue class UserId(private val value: Int)
fun sendUser1(userId: UserId) = ...
fun sendUser2(userId: Int) = ...
// Compiler error: required: UserId, found: Int. Makes sense because an Int isn't always a UserId.
sendUser1(1)
// Compiler error: required: Int, found: UserId. Does not make sense because a UserId is always an Int.
sendUser2(UserId(1))
Why doesn't the compiler see that type UserId is of type Int? It makes it harder for a project to adopt value classes if the new types aren't compatible with it's super typeFleshgrinder
09/27/2021, 1:48 PMInt
isn't the super-type of UserId
. 😉Orhan Tozan
09/27/2021, 1:50 PMhho
09/27/2021, 1:53 PMInt
types. If you want to use them interchangably, use a typealias
instead.Javier
09/27/2021, 1:57 PMOrhan Tozan
09/27/2021, 1:57 PMJavier
09/27/2021, 1:57 PMOrhan Tozan
09/27/2021, 1:58 PMJavier
09/27/2021, 1:58 PMdata class SomeClass(
val idOne: IdOne,
val idTwo: IdTho,
...
)
Javier
09/27/2021, 1:58 PMJavier
09/27/2021, 1:58 PMOrhan Tozan
09/27/2021, 1:58 PMJavier
09/27/2021, 1:58 PMJavier
09/27/2021, 1:59 PMOrhan Tozan
09/27/2021, 1:59 PMOrhan Tozan
09/27/2021, 2:06 PMvalue class UserId(private val value: Int)
fun sendUser1(userId: UserId) = ...
fun sendUser2(userId: Int) = ...
// Compiler error: required: UserId, found: Int. Makes sense because an Int isn't always a UserId.
sendUser1(1)
// Compiler error: required: Int, found: UserId. Does not make sense because a UserId is always an Int.
sendUser2(UserId(1))
wasyl
09/27/2021, 2:08 PMuserId.value
?Orhan Tozan
09/27/2021, 2:13 PMuserId.value
is the compromise I decided to make in the end, yes, but it's ugly (requires to remove the private modifier too) and feels unnecessary. But perhaps that isn't an issue for partial refactors I guess.
A UserId with supertype Int makes a UserId still a different type than the Int, so it doesn't change anything on that part.Klitos Kyriacou
09/27/2021, 2:16 PMsetMonth(mm: Int)
, and a value class Year(private val yyyy: Int)
. Then you could erroneously type setMonth(Year(1922))
- we don't want the compiler to accept that, but it would if all Years were Ints.CLOVIS
09/27/2021, 9:36 PMOrhan Tozan
09/28/2021, 2:37 PM