What is the equivalent of the below Java code in Scala:
import java.util.Random;
public class Bool {
private boolean door;
Random random = new Random();
Bool() {
this.door = random.nextBoolean();
}
}
So when a new Bool object is created, the door variable will automatically get a random Boolean value.
In Scala, the body of the class is equivalent to the methods invoked by a constructor in Java. Hence your class would look something like the following:
import java.util.Random
class Bool {
private val random = new Random
private val door = random.nextBoolean()
... // method definitions, etc.
}
(note that to be picky, since you didn't declare your Java variables final
, one could argue that the fields should be var
s here instead. Additionally, your random
field is package-protected which looks like an oversight, and would be rendered in Scala as protected[pkgName]
where pkgName
is the name of the most specific component of the class' package.)
Here is my take:
case class MyBool(door: Boolean = Random.nextBoolean)
This leaves open the possibility to create a new instance of MyBool
with a certain door value, e.g.:
val x1 = MyBool() // random door
val x2 = MyBool(true) // door set explicitly
Since there can only be two different door values, it would make sense to use static objects instead, like this:
sealed trait MyBool {
def door:Boolean
}
object MyBool {
case object True extends MyBool {
def door = true
}
case object False extends MyBool {
def door = false
}
def apply:MyBool = if(Random.nextBoolean) True else False
}
Usage:
val x1 = MyBool() // random door value
val x2 = MyBool.True // explicit door value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With