poohbar
01/02/2019, 1:47 PMUser
data class which has a type
field. The type can be either REGULAR
or ADMIN
. When it is of type ADMIN
the user will always have a not null companyId
but when it is a REGULAR
user the companyId
will always be null. Therefore the companyId
now has to be nullable and I am forced to handle it even in this case:
val user = db.getUser(id)
if (user.type == ADMIN) {
// user.companyId is definitely NOT NULL here but the compiler obviously has no idea
} else {
// user is a REGULAR user so the companyId is null
The only way around this is to have two different classes: an AdminUser
and RegularUser
that will reflect the reality more closely. Is there a better way?
In Java the compiler does not care and I get no warnings.hho
01/02/2019, 1:52 PMpoohbar
01/02/2019, 1:53 PMrarita
01/02/2019, 1:55 PMspand
01/02/2019, 1:55 PMAdminUser
and RegularUser
is duplication then maybe you should just have a val User.adminData: AdminData?
that exposes these non null valuespoohbar
01/02/2019, 1:56 PMtddmonkey
01/02/2019, 1:57 PMAdmin
type has a non-null companyId.hho
01/02/2019, 1:59 PMpoohbar
01/02/2019, 2:01 PMtype
column which determines their place in the "hierarchy". Except I didn't really model the hierarchy in my data classes.type
from kotlin and only the function that maps the db row to data class would know about it and create the correct subtype of User
Andreas Sinz
01/02/2019, 2:24 PMUser
-Table and another table Admin
with a foreign key to User
plus the companyId
?poohbar
01/02/2019, 2:28 PMuser
type
and nullable column companyId
companyId
is only null when type
is not ADMIN
nfrankel
01/02/2019, 5:39 PMpoohbar
01/03/2019, 1:46 AMnfrankel
01/03/2019, 6:52 AM