Search code examples
scalasyntaxscala-2.10scala-2.11scala-2.12

In same expression, simultaneously use value and assign variable in Scala


Is there a way in Scala to assign a variable a value and at the same time use the value in the expression? Like so...

java.lang.Math.abs(scala.util.Random.nextInt()) / {val num = java.lang.Math.pow(10, (java.lang.Math.abs(scala.util.Random.nextInt() % 5) + 1)) } * num

I got this error...

cannot be applied to (Unit)
       java.lang.Math.abs(scala.util.Random.nextInt()) / {val num = java.lang.Math.pow(10, java.lang.Math.abs(scala.util.Random.nextInt() % 7)) } * num

In order to round down to a variable exponentiation of the value '10', I want to assign some random integer to the variable "num" use the same value in an expression at same time. So then I can make sure num will be the same value for the divisor will be the same as the multiplier. I know I have seen something in scala that made me think I can do this...


Solution

  • You might put your nums in a 2-element collection and then reduce() it.

    Seq(Math.abs(util.Random.nextInt())
       ,Math.pow(10, Math.abs(util.Random.nextInt() % 5) + 1))
      .reduce((a,b) => /*use as many a's and b's as needed*/)