Arif Masrur
Arif Masrur

Reputation: 13

How to skip "ArrayIndexOutOfBoundsException: 0" from a Scala function (return type: Iterator String Array)?

I have a Scala function as shown below. Input neighborhood is array of strings. However, sometimes it (i.e. neighborhood) can be empty. In that case I get "ArrayIndexOutOfBoundsException", which is understandable. I want to avoid this exception. I mean, my code has to skip this error and move on to the next job (not shown here).

I tried this:

if(neighborhood.isEmpty){
true
} else {
      val key = neighborhood(0)
      neighborhood
        .filterNot { _.equals(key) }
        .combinations(k - 1)
}

But IntelliJ shows 'type mismatch between iterator and boolean.' How to deal with this? I am newbie in Scala. Thanks!

Here is original function:

private def scanData(neighborhood: Array[String], k: Int): Iterator[Array[String]] = {
      val key = neighborhood(0)
      neighborhood
        .filterNot { _.equals(key) }
        .combinations(k - 1)
}

```scala

Upvotes: 0

Views: 70

Answers (2)

Catalina Chircu
Catalina Chircu

Reputation: 1572

Use Option. You may find information here. Here you are en example :


object Run {
  def main(args:Array[String]):Unit = {
    val neighborhood:Array[String] = Array("1", "2","3")
    val k = 1
    val isa = geta(emptyArray) match {
      case Some(isa) => scanData(neighborhood,k)
      case None => Array.empty
    }
  }

  def scanData(neighborhood: Array[String], k: Int): Iterator[Array[String]] = {
    val key = neighborhood(0)
    neighborhood
      .filterNot { _.equals(key) }
      .combinations(k - 1)
  }

  def geta(neighborhood:Array[String]):Option[Array[String]] = {
    if(neighborhood.isEmpty){
      return None;
    } else {
      return Some(neighborhood)
    }
  }
}

Upvotes: 0

Feyyaz
Feyyaz

Reputation: 3206

You can make use of headOption for a clean approach.

neighborhood.headOption.map { key =>
  neighborhood.tail
    .filterNot(_ == key)
    .combinations(k-1)
}.getOrElse(Iterator.empty)

Upvotes: 1

Related Questions