0

I have a method below (note I have simplified to make question simpler)

def getMyInt(flag1: Boolean, flag2: Boolean): Int = {
  if (flag1) 0;
  else {
    if (flag2) 1;
    if (flag2) 2;
  }

}

Problem is that even though inner if expression returns Ints, the else that wraps will return Unit. And hence I get:

Multiple markers at this line
- type mismatch; found : Unit 
 required: Int

Any tips?

2
  • 2
    but your method can not return int. what if neither flag1 and flag2 are true? Commented Mar 31, 2013 at 17:27
  • 1
    If an if expression has no else part, it's as if you wrote if (cond) value else () (the () is the literal notation for the Unit value). The type of an if expression is the LUB (most specific common supertype) of each of its "sides." Commented Mar 31, 2013 at 17:51

2 Answers 2

8

You can try wrapping flag1 and flag2 in a Tuple and pattern match on that.

def getMyInt(flag1: Boolean, flag2: Boolean): Int = (flag1, flag2) match {
  case (true, _) => 0
  case (_, true) => 1
  //Other cases
}

Also, control flags as parameters smell funny. Martin Fowler has an article on refactoring flag arguments.

Sign up to request clarification or add additional context in comments.

Comments

3

If none of the if statements in your inner else statement apply, nothing can be returned. Change your code to as follows and it will compile:

def getMyInt(flag1: Boolean, flag2: Boolean): Int = if (flag1) 0
  else {
    if (flag2) 1
    else 2
  }

I change the second if statement in the inner else because two times if flag2 doesn't make sense.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.