Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert the following var Scala code into vals?

Tags:

scala

var exit: String = expensiveOperation
if (exit.contains(...)) exit = somethingElse

The key is I only wish to call

expensiveOperation

once since it consumes many clock cycles

like image 850
deltanovember Avatar asked Dec 04 '22 07:12

deltanovember


2 Answers

If you don’t want to expose the other val, do it inline:

val exit = {
  val result = expensiveOperation
  if (result.contains(...)) somethingElse
  else result
}

or, if you like

val exit = expensiveOperation match {
  case res if res.contains(...) => somethingElse
  case res if res.contains(...) => somethingBetter
  // ...
  case res => res
}
like image 121
Debilski Avatar answered Jan 10 '23 19:01

Debilski


a silly solution: just introduce another val.

   val expected = expensiveOperation 
   val exit = if(expected.contains(...)) expected else something else
like image 22
jilen Avatar answered Jan 10 '23 20:01

jilen