Reputation: 35
Here's an imaginary example:
class Bottle(volume: Int, water: Int) = {
def ratio = water / volume.toDouble
}
class RandomFullBottle extends Bottle(foo, foo)
^ ^
these two should be random and equal
How do I achieve this, i.e. where to call my randomBetween(a, b)
function if I don't wanna resort to passing the random value to the RandomFullBottle
constructor?
Upvotes: 1
Views: 59
Reputation: 11381
It's kind of convoluted, but this should do it.
object Bottle {
def init(): (Int, Int) = {
val r = scala.util.Random.nextInt
(r, r)
}
}
class Bottle(val volume: Int, val water: Int) {
def this(vw : (Int, Int)) {
this(vw._1, vw._2)
}
def this() {
this(Bottle.init())
}
def ratio = water / volume.toDouble
}
class RandomFullBottle extends Bottle
val randomBottle = new RandomFullBottle
println(randomBottle.ratio)
println(randomBottle.volume)
println(randomBottle.water)
Upvotes: 0
Reputation: 37852
You can create two constructors for your RandomFullBottle
class:
Bottle
constructorLike so:
class Bottle(volume: Int, water: Int) {
def ratio = water / volume.toDouble
}
class RandomFullBottle private(amount: Int) extends Bottle(amount, amount) {
def this() = this(myRandomGenerator())
}
Upvotes: 3