Return keyword inside the inline function in Scala

91 views Asked by At

I've heard about to not use Return keyword in Scala, because it might change the flow of the program like;

// this will return only 2 because of return keyword
List(1, 2, 3).map(value => return value * 2) 

Here is my case; I've recursive case class, and using DFS to do some calculation on it. So, maximum depth could be 5. Here is the model;

case class Line(
    lines: Option[Seq[Line]],
    balls: Option[Seq[Ball]],
    op: Option[String]
)

I'm using DFS approach to search this recursive model. But at some point, if a special value exist in the data, I want to stop iterating over the data left and return the result directly instead. Here is an example;

Line(
  lines = Some(Seq(
     Line(None, Some(Seq(Ball(1), Ball(3))), Some("s")), 
     Line(None, Some(Seq(Ball(5), Ball(2))), Some("d")), 
     Line(None, Some(Seq(Ball(9))), None)
  )), 
  balls = None,
  None
)

In this data, I want to return as like "NOT_OKAY" if I run into the Ball(5), which means I do not need to any operation on Ball(2) and Ball(9) anymore. Otherwise, I will apply a calculation to the each Ball(x) with the given operator.

I'm using this sort of DFS method;

def calculate(line: Line) = {
   // string here is the actual result that I want, Boolean just keeps if there is a data that I don't want
   def dfs(line: Line): (String, Boolean) = {
     line.balls.map{_.map { ball =>
        val result = someCalculationOnBall(ball)
        // return keyword here because i don't want to iterate values left in the balls
        if (result == "NOTREQUIRED") return ("NOT_OKAY", true)
        ("OKAY", false)
      }}.getOrElse(
         line.lines.map{_.map{ subLine => 
            val groupResult = dfs(subLine)
            // here is I'm using return because I want to return the result directly instead of iterating the values left in the lines
            if (groupResult._2) return ("NOT_OKAY", true)
            ("OKAY", false)
         }}
      )
  }

  .... rest of the thing
}

In this case, I'm using return keyword in the inline functions, and change the behaviour of the inner map functions completely. I've just read somethings about not using return keyword in Scala, but couldn't make sure this will create a problem or not. Because in my case, I don't want to do any calculation if I run into a value that I don't want to see. Also I couldn't find the functional way to get rid of return keyword.

Is there any side effect like stack exception etc. to use return keyword here? I'm always open to the alternative ways. Thank you so much!

0

There are 0 answers