Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala constructor

Tags:

scala

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.

like image 718
blackened Avatar asked Feb 14 '11 15:02

blackened


2 Answers

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

like image 124
Andrzej Doyle Avatar answered Oct 23 '22 23:10

Andrzej Doyle


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
like image 41
Madoc Avatar answered Oct 23 '22 22:10

Madoc