Michael de Kaste
10/07/2021, 1:51 PMJoffrey
10/07/2021, 1:54 PMgroup
won't change between 2 subsequent callsmkrussel
10/07/2021, 1:54 PMgroup
has a non trivial getter (it is calling a method on Lazy
), the compiler cannot assume that the same value will be returned on every call.Joffrey
10/07/2021, 1:55 PMfun main() {
val group: List<String>? by lazy { null }
val result = group.let {
when {
!it.isNullOrEmpty() -> it
else -> emptyList()
}
}.toSet() // no error here
}
fun main() {
val group: List<String>? by lazy { null }
val result = group?.toSet() ?: emptySet()
}
mkrussel
10/07/2021, 2:00 PMval result = group?.toSet().orEmpty()
Michael de Kaste
10/07/2021, 2:18 PMmkrussel
10/07/2021, 2:22 PMlistOfNotNull(group, group2, group3).firstOrNull()?.toSet().orEmpty()
Joffrey
10/07/2021, 2:23 PMwhen
expression like this. For instance:
fun main() {
val group1: List<String>? by lazy { null }
val group2: List<String>? by lazy { null }
val group3: List<String>? by lazy { null }
val geldigePrestaties = listOf(group1, group2, group3).firstOrNull { !it.isNullOrEmpty() }?.toSet().orEmpty()
}
mkrussel
10/07/2021, 2:25 PMMichael de Kaste
10/07/2021, 2:26 PMJoffrey
10/07/2021, 2:27 PMfun main() {
val group1: List<String>? by lazy { null }
val group2: List<String>? by lazy { null }
val group3: List<String>? by lazy { null }
val groups = sequence {
yield(group1)
yield(group2)
yield(group3)
}
val geldigePrestaties = groups.firstOrNull { !it.isNullOrEmpty() }?.toSet().orEmpty()
}
Michael de Kaste
10/07/2021, 2:27 PMmkrussel
10/07/2021, 2:28 PMval geldigePrestaties: Set<String> = (group.takeUnless { it.isNullOrEmpty() }
?: group2.takeUnless { it.isNullOrEmpty() }
?: group3.takeUnless { it.isNullOrEmpty() }
)?.toSet().orEmpty()
Joffrey
10/07/2021, 2:30 PMMichael de Kaste
10/07/2021, 2:36 PMJoffrey
10/07/2021, 2:40 PMwhen
-based approach here, because semantically you're considering these groups as a collection of things that you're searching. All branches of the when
are the same because of the semantics of what you're doing, that's why I personally find it cleaner to have this "search for a good group" apparent as a search through a collection/sequence.lazy
in a special way (which could indeed be nice!), I would still prefer the sequence approach here.ephemient
10/07/2021, 4:43 PMgroup1?.ifEmpty { null }
?: group2?.ifEmpty { null }
?: group3?.ifEmpty { null }
?: emptyList()