val arr = Array.fill[String](6, 6)("dark")
安全得到:
arr(9)(9)
>java.lang.ArrayIndexOutOfBoundsException: 9
我用了类似的东西(但很难看):
arr.lift(2).flatMap(_.lift(2))
>res0: Option[String] = Some(dark)
有更好的方法吗?
如果你想要更易读的内容,你可以使用a来理解:
for {
inner <- arr.lift(7)
value <- inner.lift(2)
} yield value
把我的评论变成答案:
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