Michael Marshall
09/21/2021, 5:33 PMdata class Foo(val a: String? = null, val b String? = null)
I could write
data class Foo(val a: String? = null, val b String? = null)
{
init {
requireNotNull(a ?: b)
}
}
But this only causes a crash at runtime. How do I achieve the same result with compile time safety?Joffrey
09/21/2021, 5:35 PMa
or non-null b
), and make the primary constructor privatea
and b
are exclusive, maybe a sealed class
would better express it (easier to use after construction).
sealed class Foo {
data class A(val a: String): Foo()
data class B(val b: String): Foo()
}
If both a
and b
can be specified, it depends on semantics I guess (you could add a third child class with both args, or just use factory methods instead of a sealed class hierarchy). What are the accepted configurations?Michael Marshall
09/21/2021, 5:52 PMJoffrey
09/21/2021, 5:55 PMMichael Marshall
09/21/2021, 5:55 PMa
and b
are not exclusive, however at least one must not be null. So these are allowed:
• a, b
• a, null
• null, bRob Elliot
09/21/2021, 5:57 PMMichael Marshall
09/21/2021, 6:00 PMif (a != null || b != null) {
Foo(a,b)
}
instead of needing to do something like
when {
a != null && b != null -> Foo(a,b)
a != null -> Foo(a)
b != null -> Foo(b)
}
so I can later get a
or b
without a null check, e.g.
data class Foo(val a: String? = null, val b String? = null) {
fun getValue(): String = a ?: b
}
Joffrey
09/21/2021, 6:21 PMMichael Marshall
09/21/2021, 6:26 PMRob Elliot
09/21/2021, 9:32 PMif (a != null || b != null) {
Foo(a,b)
}
the compiler can’t know which of a & b ends up being not null, so within it both will still be of type String?
. So you will have to call a function (whether factory or constructor) that accepts both as String?
.Morgan Pittkin
09/21/2021, 9:48 PMcompanion object {
fun foo(a: A) = Foo(a, null)
fun foo(b: B) = Foo(null, b)
fun foo(a: A, b: B) = Foo(a, b)
}
andylamax
09/22/2021, 1:35 AMMichael Marshall
09/22/2021, 1:38 AMcompanion object {
fun fooA(a: String) = Foo(a, null)
fun fooB(b: String) = Foo(null, b)
fun foo(a: String, b: String) = Foo(a, b)
}
Morgan Pittkin
09/22/2021, 1:50 AMandylamax
09/22/2021, 3:20 AMTobias Berger
09/22/2021, 7:42 AMMichael Marshall
09/22/2021, 7:44 AMfun getValue()
to be nullable, and then handling the null case where it’s called.Nolan
09/23/2021, 3:07 PMprimary
and secondary
, with primary
being non-null and secondary
being nullable? or another way to think of it -- make "light" non-null, and "dark" nullable. if you only have one image, does the light/dark differentiation mean anything?Michael Marshall
10/06/2021, 8:25 AMprimary
.Nolan
10/19/2021, 5:59 PM