Aleksiv95
Aleksiv95

Reputation: 35

Calculations before extending class

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

Answers (2)

Kien Truong
Kien Truong

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

Tzach Zohar
Tzach Zohar

Reputation: 37852

You can create two constructors for your RandomFullBottle class:

  • A private constructor that takes an int and passes it to the parent Bottle constructor
  • A public one that takes no arguments, generates the random value and passes it to the private constructor

Like 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

Related Questions