Scala constructor

Which is equivalent to the following 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 automatically gets an arbitrary boolean value.

+6
scala
source share
3 answers

In Scala, the body of a class is equivalent to the methods called by the constructor in Java. Therefore, your class will look something like this:

 import java.util.Random class Bool { private val random = new Random private val door = random.nextBoolean() ... // method definitions, etc. } 

(note that in order for you not to declare your Java final variables, it can be argued that var should be here instead. In addition, the random field is protected by a package that looks like supervision, and will be displayed in protected[pkgName] as protected[pkgName] in Scala protected[pkgName] , where pkgName is the name of the most specific component of the class package.)

+11
source share

Here is my trick:

 case class MyBool(door: Boolean = Random.nextBoolean) 

You will be able to create a new instance of MyBool with a specific door value, for example:

 val x1 = MyBool() // random door val x2 = MyBool(true) // door set explicitly 

Since there can only be two different door values, it would be advisable to use static objects, for example:

 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 } 

Using:

 val x1 = MyBool() // random door value val x2 = MyBool.True // explicit door value 
+5
source share

Closer scala code should be:

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

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

+3
source share

All Articles