blackened
blackened

Reputation: 387

Scala constructor

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.

Upvotes: 6

Views: 5659

Answers (3)

Madoc
Madoc

Reputation: 5919

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

Upvotes: 5

Nicolas
Nicolas

Reputation: 24759

The closer scala code should be:

class Bool {
  var random = new Random
  private var door = random.nextBoolean
}

Even if the public random field does not look as a good idea.

Upvotes: 3

Andrzej Doyle
Andrzej Doyle

Reputation: 103777

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 vars 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.)

Upvotes: 11

Related Questions