\$\begingroup\$
\$\endgroup\$
Simple extension method for Kotlin. Should perform an action on every element in a 2d array. i.e. An array of arrays.
I have made the assumption that because the receiver type is defined as an array of arrays of type T, that I do not need to do any checks or casts.
fun <T> Array<Array<T>>.forEach2d(action: (T) -> Unit): Unit {
for (outer in this) {
for (inner in outer) {
action(inner)
}
}
}
1 Answer 1
\$\begingroup\$
\$\endgroup\$
0
s/forEach2d/forEach2D/
- Make it an inline function for performance reasons.
- Consider renaming
outer
andinner
. At first glance a reader might think thatouter
andinner
refer to the outer array and an inner array but this isn't the case asouter
is in fact an inner array andinner
is an element in an inner array. e.g.s/outer/array/g/
ands/inner/element/g
. - Optionally omit the braces on the 'for' loops. I don't feel strongly about this one either way. I personally keep them but for something as simple as this where there really isn't any logic it makes me wonder why explode it into so many lines. However, I've worked on teams where it is our convention to always use braces for if/for/etc. constructs so be consistent above being brief.
- Document your Kotlin Code. It may seem like a small thing but it can also be surprisingly amazing how much more real/professional/reusable/etc. your code is once you and others can discover methods and documentation is right there explaining exactly what it does and doesn't do.
Example:
/**
* Performs the given [action] on each element in each array.
*/
inline fun <T> Array<Array<T>>.forEach2D(action: (T) -> Unit): Unit {
for (array in this) for (element in array) action(element)
}
answered Jul 5, 2016 at 21:56
default