Reputation: 51
for example
val coordinates: Array<IntArray> = [[1, 2], [1, 3], [1, 4]]
coordinates
.map {it[0]}
.all {it == x[0]}
x means the map result of coordinates. I want use it in the 'all' step, how to do that?
Upvotes: 1
Views: 67
Reputation: 270995
If I understand correctly, you can just declare a val
called x
:
val x = coordinates.map { it[0] }
val result = x.all { it == x[0] }
Or if you want to do it in one expression, you can use the scope function run
or let
:
val result = coordinates.map { it[0] }.run {
all { it == this[0] }
}
or:
val result = coordinates.map { it[0] }.let { x ->
x.all { it == x[0] }
}
Though, if you just want to check if the whole list has exactly one unique value, I think this is more readable:
val result = coordinates.map { it[0] }.distinct().size == 1
The above doesn't short-circuit like all
. A shortcircuiting version would need Sequence
:
val result = coordinates
.asSequence()
.map { it[0] }
.distinct().take(2).count() == 1
Upvotes: 1
Reputation: 23164
You could just write this
coordinates
.map {it[0]}
.all {it == coordinates[0][0]}
Or if you don't want to directly refer to coordinates again, maybe insert a let
like
coordinates
.map { it[0] }
.let { x -> x.all { it == x[0] } }
Although for your specific use case I probably would just do
coordinates
.all { it[0] == coordinates[0][0] }
Upvotes: 1