3
val arr = Array.fill[String](6, 6)("dark")

Unsafe get:

 arr(9)(9)
>java.lang.ArrayIndexOutOfBoundsException: 9

I use something like that (but ugly):

arr.lift(2).flatMap(_.lift(2))

>res0: Option[String] = Some(dark)

Is there better way?

1
  • 2
    Define a safeGet[T](x:Int, y:Int):Option[T], using whatever code you like (an explicit array-bounds check might be clearest), then make it an implicit operation on Array. Then the ugliness is just in one place... Commented Aug 2, 2015 at 9:04

2 Answers 2

4

If you want something more readable, you could use a for comprehension:

for {
 inner <- arr.lift(7)
 value <- inner.lift(2)
} yield value
Sign up to request clarification or add additional context in comments.

Comments

2

Turning my comment into an answer:

val arr = Array.fill[String](6, 6)("dark")

implicit class SafeArrayOps[T](arr: Array[Array[T]]) {
  def safeGet(x: Int, y: Int) = {
    if (x < 0 || x >= arr.length) None
    else {
      val inner = arr(x)
      if (y <= 0 || y >= inner.length) None
      else Some(inner(y))
    }
  }
}

arr.safeGet(2,2)                                //> res0: Option[String] = Some(dark)
arr.safeGet(7,7)                                //> res1: Option[String] = None
arr.safeGet(2,7)                                //> res2: Option[String] = None
arr.safeGet(7,2)                                //> res3: Option[String] = None
arr.safeGet(-1, 2)                              //> res4: Option[String] = None
arr.safeGet(2,-1)                               //> res5: Option[String] = None

3 Comments

Brilliant! Combining it with @sascha-kolberg answer it looks even better, I think.
I'm not too bothered about how it looks. I subscribe to the advice of amazon.co.uk/Elements-Programming-Style-Brian-Kernighan/dp/… "Say what you mean simply and directly".
@TheArchetypalPaul I am too bothered about how it looks.

Your Answer

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.