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)
        }
    }
}
\$\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)
}
\$\endgroup\$
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.