Haryo Bimo
Haryo Bimo

Reputation: 13

Filter a range in kotlin

In kotlin I want filter a range of Int to make odd/even example. so I made a listOf range 1..50

val angka = listOf(1..50)

followed by applying filter for even and filterNot for odd

val genap = angka.filter { it % 2 == 0}
val ganjil = angka.filterNot { it % 2 == 0 }

then printing both the even/odd lists

println("Genap = $genap")
println("Ganjil = $ganjil")

I do not see any problems with code, but it does throws exception mentioned below

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public inline operator fun BigDecimal.mod(other: BigDecimal): BigDecimal defined in kotlin

Upvotes: 1

Views: 502

Answers (3)

Eduard Tomek
Eduard Tomek

Reputation: 374

Your declaration of all numbers is wrong... it is like this val angka: List<IntRange> = listOf(1..50). You created a list of ranges contaning one range.

This should work:

val angka = 1..50
val genap = angka.filter { it % 2 == 0}
val ganjil = angka.filterNot { it % 2 == 0 }
println("Genap = $genap")
println("Ganjil = $ganjil")

Upvotes: 0

Joffrey
Joffrey

Reputation: 37680

This is creating a List<IntRange> with a single element:

val angka = listOf(1..50)

You should instead directly filter the range:

val angka = 1..50

The rest of the code is correct.

Upvotes: 1

AlexT
AlexT

Reputation: 2964

If you are a beginner with Kotlin, please either specify the type of values explicitly, or turn on the local variable type hits.

This way you would have noticed that the code is not perfect. Your list angka is not a list of type List<Int>, but a list of type List<IntRange>.

Meaning that you are not doing Int % 2 == 0, but in fact, you are doing IntRange % 2 == 0.

If you want to get a list from a range, you need to do (x..y).toList(). So your code will be:

val angka = (1..50).toList() //or since you are not using this list anywhere else, just leave it as `1..50` and the filter will work fine on the IntRange.

val genap = angka.filter { it % 2 == 0 }
val ganjil = angka.filterNot { it % 2 == 0 }

println("Genap = $genap")
println("Ganjil = $ganjil")

With output:

Genap = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50]
Ganjil = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]

Upvotes: 1

Related Questions