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"
^