Suppose a Scala class has a type which is defined in a subclass. How it should be referred from another class?
Below is the CurrencyZone sample from the Scala book.
Which type should I use for the argument of a method log(currency:???) that just prints an amount of the given currency?
Something like this:
object CurrencySample {
def main(args: Array[String]): Unit = {
log(Europe.Euro)
log(US.Dollar)
}
def log(currency: /* Which currency type should be used there?*/): Unit = { }
}
abstract class CurrencyZone {
type Currency <: AbstractCurrency
val CurrencyUnit: Currency
def make(amount: Long): Currency
abstract class AbstractCurrency {
def designation: String
def amount: Long
def +(that: Currency): Currency = make(this.amount + that.amount)
def *(number: Double): Currency = make((number * this.amount).toLong)
}
}
object Europe extends CurrencyZone {
val Cent = make(1)
val Euro = make(100)
val CurrencyUnit = Euro
type Currency = Euro
override def make(cents: Long) = new Euro {
override def amount = cents
}
abstract class Euro extends AbstractCurrency {
override def designation = "EUR"
}
}