https://kotlinlang.org logo
#announcements
Title
# announcements
b

Bernhard

09/18/2019, 8:59 AM
is there a nice way to only take x elements from a sequence if x >= 0, otherwise return everything? Thinking of an extension function atm
s

spand

09/18/2019, 9:01 AM
Isnt that
take
?
b

Bernhard

09/18/2019, 9:02 AM
take checks for non negative ints
require(n >= 0) { “Requested element count $n is less than zero.” }
s

spand

09/18/2019, 9:02 AM
Oh, I misunderstood
b

Bernhard

09/18/2019, 9:02 AM
otherwise I’d go for something like:
Copy code
private fun <T> Sequence<T>.limitIfPositive(size: Int): Sequence<T> =
    if (size >= 0) {
        this.take(size)
    } else {
        this
    }
s

spand

09/18/2019, 9:04 AM
I cant wrap my head around that behaviour. Why do you want that as opposed to empty ?
b

Bernhard

09/18/2019, 9:08 AM
existing API requires an integer to limit for size
I’m refactoring atm
I want the limit to optional at some point
so rather than breaking everything now by making the limit nullable I’d go for: negative limit means no limit
then at some point make limit nullable
4 Views