1
\$\begingroup\$

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)
 }
 }
}
asked Jun 14, 2016 at 10:06
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$
  1. s/forEach2d/forEach2D/
  2. Make it an inline function for performance reasons.
  3. Consider renaming outer and inner. At first glance a reader might think that outer and inner refer to the outer array and an inner array but this isn't the case as outer is in fact an inner array and inner is an element in an inner array. e.g. s/outer/array/g/ and s/inner/element/g.
  4. 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.
  5. 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
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.