Safe Range Operator in Groovy?

Is there a safe range operator for Groovy?

For example, if I have

[1,2,3][0..10] 

Groovy will throw java.lang.IndexOutOfBoundsException:

Is there an index-safe way to access this range? Or do I always need to check the size of the collection before starting the range?

+4
source share
1 answer

You can use take(n) , which allows you to accept up to a certain number of elements without errors, if the collection:

 def input = [1,2,3] def result = input.take(10) assert result == [1,2,3] input = [1,2,3,4,5] result = input.take(4) assert result == [1,2,3,4] 

If you need to start with an offset, you can use drop(n) , which does not change the original collection:

 def input = [1,2,3,4,5] def result = input.drop(2).take(2) assert result == [3,4] 

They are both protected from collection size. If in the last example the list is too small, you can have only one or zero element in the collection.

+7
source

Source: https://habr.com/ru/post/1489595/


All Articles