[英]What is the Scala syntax for instantiating using a specific implementation?
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? 使用MarketImpl实现实例化TraitTest的语法是什么? Conceptually something like the following
概念上类似以下内容
new TraitTest with MarketImpl
Although the above does not work because MarketImpl is not a trait 尽管以上操作无效,因为MarketImpl不是特质
Both TraitTest
and MarketImpl
are classes. TraitTest
和MarketImpl
都是类。 Scala cannot inherit from multiple classes. Scala不能从多个类继承。 You should refactor your code, eg making
TraitTest
a trait. 您应该重构代码,例如使
TraitTest
成为特征。 Then you could write new MarketImpl with TraitTest
. 然后,您可以
new MarketImpl with TraitTest
编写new MarketImpl with TraitTest
。
You've hit the single class inheritance limit of Scala (and Java). 您已经达到了Scala(和Java)的单一类继承限制。 You can fix it using instance composition/aggregation (in the same way you would using Java):
您可以使用实例组合/聚合来修复它(与使用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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.