More Library Functions

Helper functions might look confusing at first, but after some time one usually finds them incredibly useful.

Converting a Collection into a Sequence isn’t the only way to get the latter one. The standard library contains the generateSequence() function which lets you specify how to compute each new element.

With generateSequence() you may generate an infinite sequence of natural numbers. You pass the first element in a sequence as an argument. Another argument is a lambda, which defines how each new element should be computed based on the previous element:

// MoreLibraryFunctions/NumberSequence1.kt import atomictest.eq fun main(args: Array<String>) { val naturalNumbers = generateSequence(1) { it + 1 } naturalNumbers.take(3).toList() eq listOf(1, 2, 3) naturalNumbers.take(10).count() eq 10 }

Note that Sequence doesn’t have a property size which is regular for Collections, instead you can call count() function which emphasizes that it’s the terminal operation and all the elements will be actually counted rather than a stored value will be returned.

End of sample. See for full early-access book.

Previous          Next

©2018 Mindview LLC. All Rights Reserved.