Reputation: 3486
I have just started learning kotlin, and I stumbled upon this small issue. I have a list of Objects, and am filtering the list within a specified range. Am able to get the objects with in the range, but when I changed the range to outer bound, am getting an empty array,
So to keep the question simple, lets say am having a list of integers like
original list [1, 2, 3, 4, 5, 6, 7]
and am having a dropper function, which filters out the elements
working condition
fun dropper(args: ArrayList<Int>): List<Int> {
return args.filter { it in 2..6 } // it >= 2 && it <= 6
}
output is received as
[2, 3, 4, 5, 6]
but when I change the range to
fun dropper(args: ArrayList<Int>): List<Int> {
return args.filter { it in 4..2 } // it <= 2 && it >= 4
// it in 4..2 , was suggested by the IDE
}
getting output as an empty list.
Am pretty much sure that the list value is not clearing, because after this function is called am passing the list to an other operation which gives the intended result.
Upvotes: 2
Views: 2211
Reputation: 17809
Use downTo
. read Ranges for detailed description.
Range (x..y
), here x is starting index and y is last and it goes incremental way. So 1..10
range have 10 elements but 10..1
looks from 10 on-wards so it is an empty range. You need to use downTo
operator.
Change your code like following:
fun dropper(args: ArrayList<Int>): List<Int> {
return args.filter { it in 4 downTo 2 } // it <= 2 && it >= 4
}
Upvotes: 1
Reputation: 3486
Other than these answers, I also found out that !
operation works as well
fun dropper(args: ArrayList<Int>): List<Int> {
return args.filter { it !in 2..4 } // it <= 2 && it >= 4
}
Upvotes: 1
Reputation: 809
Hello you need to use operator downTo
fun main(args: Array<String>) {
var list = arrayListOf<Int>(1, 2, 3, 4, 5, 6, 7)
println(dropper(list)) // [2, 3, 4]
}
fun dropper(args: ArrayList<Int>): List<Int> {
return args.filter { it in 4 downTo 2 } // [2, 3, 4]
}
Here is fully described how to use ranges. - https://kotlinlang.org/docs/reference/ranges.html#ranges
Upvotes: 1
Reputation: 89548
4..2
is basically an empty range, because it translates to it >= 4 && it <= 2
. To create a range that's decrementing, you have to use downTo
:
args.filter { it in 4 downTo 2 }
reversed
can also be an alternative in some cases:
args.filter { it in (2..4).reversed() }
This specific problem is also the first example in Dan Lew's recent blog post that covers ranges nicely.
Upvotes: 3