0

I am new to scala and not able to get the better way to do a thing without if and else statement. As immutability is the way to go in scala and its not recommended to use var, how will we implement the following without using var

var requests = callFunc1()
if requests.isEmpty requests = callFunc2()

def callFunc1(): List[Int]
def callFunc2(): List[Int]
0

3 Answers 3

8

Going the the requirements you list, and the semantics you show in the example (e.g. evaluate callFunc1 once, evaluate callFunc2 once if and only if callFunc1 evaluates to Nil) The following meets your requirements.

val requests = callFunc1 match {
  case Nil => callFunc2
  case nonempty => nonempty
}

However, I don't think there is anything particularly wrong with using if and a temporary value either.

val requests = {
  val f1 = callFunc1
  if (f1.isEmpty) callFunc2 else f1
}
Sign up to request clarification or add additional context in comments.

Comments

2

You may use additional container filtering it, and use getOrElse:

val requests = Option(func1()).filter(_.nonEmpty).getOrElse(func2())

1 Comment

What I like about this answer is that it lifts whether or not the list is valid into a datatype other than the direct representation - func1 is a possibly invalid return value, Some(func1).filter(_.nonEmpty) is either an invalid result None, or a valid result Some(validlist)
2

The answer from Martijn is very good if the functions definitions are fixed. An alternative is to change the signature of callFunc1 so that it returns Option[List[Int]] and then use

val requests = callFunc1().getOrElse(callFunc2())

def callFunc1(): Option[List[Int]]
def callFunc2(): List[Int]

The advantage of returning an Option is that you can distinguish between "I failed to read the list" (None) and "I read the list but it was empty" (Some(List())).

The choice will depend on the wider structure of the program, and it depends on what getFunc1 is actually doing and why it might return an empty List. For example, if the data comes from a Map or a File operation, it probably comes wrapped in an Option anyway so returning the Option might simplify that code as well.

Note that you can convert a List to Option[List] like this:

Option(list).filter(_.nonEmpty)

This will return None if list is empty or null, otherwise it will return Some(list).

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.