Suppose I have the following trait
trait Market {
def getCurrency: String
}
With the following implementation
class MarketImpl extends Market {
override def getCurrency = "USD"
}
I have another abstract class as follows
abstract class TraitTest extends Market {
}
What is the syntax for instantiating TraitTest using the MarketImpl implementation? Conceptually something like the following
new TraitTest with MarketImpl
Although the above does not work because MarketImpl is not a trait
Both TraitTest
and MarketImpl
are classes. Scala cannot inherit from multiple classes. You should refactor your code, eg making TraitTest
a trait. Then you could write new MarketImpl with TraitTest
.
You've hit the single class inheritance limit of Scala (and Java). You can fix it using instance composition/aggregation (in the same way you would using Java):
abstract class TraitTest extends Market {
def getCurrency = market.getCurrency
val market: Market
}
and then you instantiate:
val myTraitTest = new TraitTest {
val market = new MarketImpl
}
scala> myTraitTest.getCurrency
res1: String = USD
如果打算与其他类一起实例化MarketImpl
请MarketImpl
成为一个trait
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.