0

I want to declare a constant value MyValue of type string using the result of an anonymous function. Right now I have something similar using a declared function getValue

// Start writing your ScalaFiddle code here
val n = 23

def getValue(): String = {
  if (n == 1) return "One"
  if (n == 2) return "Two"
  return "Another value"
}

val MyValue = (getValue())

println(n)
println(MyValue)

How could I use an anonymous function instead? So it would look like this

val n = 23

val MyValue = (() => {
  if (n == 1) return "One"
  if (n == 2) return "Two"
  return "Another value"
})()

println(n)
println(MyValue)

But this gives me the following error:

ScalaFiddle.scala:7: error: return outside method definition
    if (n == 1) return "One"
                ^
ScalaFiddle.scala:8: error: return outside method definition
    if (n == 2) return "Two"
                ^
ScalaFiddle.scala:9: error: return outside method definition
    return "Another value"
    ^
akko
  • 559
  • 3
  • 8
  • 17
  • 2
    Don't use `return` in Scala. More details in [this blog post](https://tpolecat.github.io/2014/05/09/return.html). [This answer](https://stackoverflow.com/questions/17754976/scala-return-statements-in-anonymous-functions) might also help. – Oleg Pyzhcov Apr 15 '21 at 18:12
  • 1
    Why a lambda of no arguments that you want to call immediately? Why not just assign the whole `if` expression to your value? – Luis Miguel Mejía Suárez Apr 15 '21 at 18:18

1 Answers1

2

You can remove return and use else in the conditionals:

val MyValue = (
    () => {
        if (n==1) "One" 
        else if (n==2) "Two" 
        else "Another value"
    }
)()
mck
  • 40,932
  • 13
  • 35
  • 50