2

If Java I could legally do this...

int num = 5;
final boolean isPositive;
if(five > 0) {
  isPositive = true;
} else {
  isPositive = false;
}
System.out.println("Is positive: " + isPositive); // Prints "Is positive: true"

I call these delayed definition constants.

Is there a way to create delayed definition constants in Scala?

Michael Lafayette
  • 2,972
  • 3
  • 20
  • 54
  • 1
    AFAIK you can't do that in Scala; but one could use [lazy vals](http://stackoverflow.com/questions/9449474/def-vs-val-vs-lazy-val-evaluation-in-scala) in a similar way. – rsenna Feb 03 '16 at 17:05
  • `lazy val` isn't relevant here IMO. – Seth Tisue Feb 03 '16 at 18:00

3 Answers3

6

In scala you can't delay the definition. If you wanted to do something similar then you would typically achieve this by assigning it to the result of the if statement.

val isPositive = if(num > 0) true else false

or even just

val isPositive = num > 0
StuartMcvean
  • 450
  • 2
  • 8
  • Maybe worth adding that Java semantics of if statements and closing over values requires the Java idiom. And that final and constant are different concepts. – som-snytt Feb 03 '16 at 17:32
2

You can do something like this:

val isPositive = num > 0

or (when num is hard to compute and might not be called - then you can delay computation)

lazy val isPositive = num > 0

if the num is a variable then you can write:

def isPositive = num > 0

In Scala it's perfectly OK to write short functions as one liners.

wlk
  • 5,695
  • 6
  • 54
  • 72
1

I did it like this...

val num = 5
val isPositive: Boolean = {
  if(num > 0) { true }
  else { false }
}
println("Is positive: " + isPositive) // Prints "Is positive: true"
Michael Lafayette
  • 2,972
  • 3
  • 20
  • 54