Home > OS >  How to handle returns correctly in Scala
How to handle returns correctly in Scala

Time:11-29

I'm new to Scala and I'm trying to do the following:

I had such function:

  def terrainFunction(levelVector: Vector[Vector[Char]]): Pos => Boolean = {
    (pos: Pos) => if (levelVector(pos.row)(pos.col) == '-') false else true
  }

But I want to catch all the errors in the returned function and return false from it instead of throwing an exception.

So I tried to do this way:

  def terrainFunction(levelVector: Vector[Vector[Char]]): Pos => Boolean = {
    val terrFunc = (pos: Pos) => if (levelVector(pos.row)(pos.col) == '-') false else true

    (pos: Pos) =>
      try {
        return terrFunc(pos)
      } catch {
        return false
      }
    
  }

The thing is that I get compiler error:

Type mismatch.
Required: Pos => Boolean
Found: Boolean

Why does compiler think that I'm returning Boolean, not a whole this function:

    (pos: Pos) =>
      try {
        return terrFunc(pos)
      } catch {
        return false
      }

And how to fix that?

CodePudding user response:

Don't use try nor return, rather use proper data types like Try.

import scala.util.Try

def terrainFunction(levelVector: Vector[Vector[Char]]): Pos => Boolean =
  (pos: Pos) =>
    Try(levelVector(pos.row)(pos.col) != '-').getOrElse(false)
  • Related