开发者

What is the Scala syntax for instantiating using a specific implementation?

开发者 https://www.devze.com 2023-04-05 01:22 出处:网络
Suppose I have the following trait trait Market { def getCurrency: String } With the following 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 t开发者_开发百科he 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, e.g. 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


Make MarketImpl a trait if you plan to instantiate it together with other classes.

0

精彩评论

暂无评论...
验证码 换一张
取 消