Scala shorthand for declaring and returning a variable

123 views Asked by At

Just for curiosity is there a shorthand for

test = "test"
test

I tried something like that

(test = "test")

or

//if ((test = "test") != null) test
if (test = "test") test

//edit: I have to set test variable before I return it.

2

There are 2 answers

0
zio On BEST ANSWER

According to https://stackoverflow.com/a/8845459/3641692 it is not possible

I have to do it on multiple lines:

var test: String = null

def setter(t:String): String = {
  test = t
  test
}
0
Daenyth On

Your example doesn't make much sense. If you're inside some scope, vars/vals/defs inside that scope are not accessible from outside that scope - so there's no need for this. You'd just return the value (using implicit return).

"test"