jhamm
jhamm

Reputation: 25032

Scala always returning true....WHY?

I am trying to learn Scala and am a newbie. I know that this is not optimal functional code and welcome any advice that anyone can give me, but I want to understand why I keep getting true for this function.

  def balance(chars: List[Char]): Boolean = {
    val newList = chars.filter(x => x.equals('(') || x.equals(')'));
    return countParams(newList, 0)
  }                                               

  def countParams(xs: List[Char], y: Int): Boolean = {
    println(y + " right Here")
    if (y < 0) {
      println(y + " Here")
      return false
    } else {
      println(y + " Greater than 0")
      if (xs.size > 0) {
        println(xs.size + " this is the size")
        xs match {
          case xs if (xs.head.equals('(')) => countParams(xs.tail, y + 1)
          case xs if (xs.head.equals(')')) => countParams(xs.tail, y - 1)
          case xs => 0
        }
      }
    }
    return true;
  }
  balance("()())))".toList)

I know that I am hitting the false branch of my if statement, but it still returns true at the end of my function. Please help me understand. Thanks.

Upvotes: 2

Views: 886

Answers (2)

MushinNoShin
MushinNoShin

Reputation: 4886

The if in scala is an expression. It returns a value and is conceptually similar to the ternary if in other languages.

If you want to return something in your else branch, you should have an else for the nested if and allow that to return a value.

In other words, countParams is evaluating all of that code and falling to the very last line in the block (the {}) that is being assigned to countParams. That is, the true;

In short, lose the true at the end of countParams, and give your nested if an else that returns something meaningful.

Upvotes: 2

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

You either must be more explicit in what you are returning or make it more explicit for the compiler. This works:

def countParams(xs: List[Char], y: Int): Boolean = {
    println(y + " right Here")
    if (y < 0) {
      println(y + " Here")
      false
    } else {
      println(y + " Greater than 0")
      if (xs.size > 0) {
        println(xs.size + " this is the size")
        xs match {
          case xs if (xs.head.equals('(')) => countParams(xs.tail, y + 1)
          case xs if (xs.head.equals(')')) => countParams(xs.tail, y - 1)
          case xs => false
        }
      } else {
        true
      }
    }
}

In the code above each branch of if returns some value so the compiler assumes it's a value to be returned. BTW version without logging and much more idiomatic:

def countParams(xs: List[Char], y: Int) =
    xs match {
        case Nil => y == 0
        case '(' :: rest => countParams(rest, y + 1)
        case ')' :: rest if(y > 0) => countParams(rest, y - 1)
        case _ => false  //must be closing parens but y < 0
    }

Upvotes: 3

Related Questions