https://kotlinlang.org logo
#android
Title
# android
u

uhe

07/24/2017, 3:43 PM
@scruffyfox It's also worth checking out lazy `Sequence`s and the various transformation operations like
map
,
flatMap
etc I often find these easier to process than "oldschool" java loops. Just to give you an idea (completely untested and may not meet your needs):
Copy code
fun searchParent(id: String): Module? =
        modules
                .asSequence()
                .mapNotNull { searchParent(it, id) }
                .firstOrNull()

fun searchParent(root: Module, id: String): Module? =
        root.steps
                ?.asSequence()
                ?.flatMap { it.steps?.asSequence() ?: emptySequence() }
                ?.firstOrNull { it.id == id }
s

scruffyfox

07/25/2017, 7:07 AM
surely with mapNotNull will iterate through every item regardless if it has found the parent or not? so would be much more inefficient than doing the original loop and returning once found? also why add
.asSequence()
,
modules
is already type
List<Module>
so surely that is redundant?
u

uhe

07/25/2017, 8:13 AM
that's the thing about sequences. they're evaluated lazily.
e.g.
Copy code
val list = listOf(1, 2, 3, 4, 5)
    val result = list
            .asSequence()
            .mapNotNull {
                println("mapping $it")
                if (it == 3) 3 else null
            }
            .firstOrNull()
    println(result)
this will stop iterating once a non-null value is found
it's really quite beautiful, once you've wrapped your head around it