jwass
10/27/2021, 1:56 PMsealed class Resolvable<T>
class Resolved<T>(val value: T, val pk: Long) : Resolvable<T>()
class Unresolved<T>(val value: T) : Resolvable<T>() {
fun resolved(pk: Long) = Resolved(value, pk)
}
Now I want to take a Collection<Resolvable<ItemIdentifier>>
and filter only unresolved ones, into a Collection<Unresolved<ItemIdentifier>>
.
This works:
val x : Collection<Unresolved<ItemIdentifier>> = itemIdentifiers.mapNotNull { when(it) {is Unresolved -> it else -> null }}
But I wonder if there's a more idiomatic way to do it? (type annotation on x
just for clarity).Orhan Tozan
10/27/2021, 2:09 PMval x: Collection<Unresolved<ItemIdentifier>> = itemIdentifiers.filterIsInstance<Unresolved<ItemIdentifier>>()
jwass
10/27/2021, 3:04 PMsealed class Resolvable<T> {
/** There's a value in either case.
*/
fun unwrap(): T = when (this) {
is Resolved -> this.value
is Unresolved -> this.value
}
fun unwrap2(): T =
if (this is Resolved<T>) {
this.value
} else if (this is Unresolved<T>) {
this.value
}
}
data class Resolved<T>(val value: T, val pk: Long) : Resolvable<T>()
data class Unresolved<T>(val value: T) : Resolvable<T>()
My compiler is happy with the unwrap()
when I write it with a when
. But with an if
there's a problem with the else
branch, and it thinks that the return type is Unit
not T
. Any ideas why the when
version is OK but the if
version is not?Orhan Tozan
10/28/2021, 10:20 AMjwass
10/28/2021, 10:20 AMif
?dave08
10/28/2021, 11:57 AMelse error("Invalid case")
after that if
, it should work.jwass
10/28/2021, 2:05 PMwhen
.Tobias Suchalla
10/29/2021, 6:10 AMsealed class Resolvable<T> {
abstract val value: T
}
data class Resolved<T>(
override val value: T,
val pk: Long
) : Resolvable<T>()
data class Unresolved<T>(
override val value: T
) : Resolvable<T>()
That way there is always a value
on a Resolvable<T>
, no need to unwrap.jwass
11/23/2021, 9:00 AM