比方说,我的项目中有很多汽车对象,例如:
object Porsche extends Car {
override def start() {...}
override def canStart(fuelInLitr: Int) = fuelInLitr > 5
override val fuelInLitr = 45
override val carId = 1234567
}我扩展汽车,这只是设置一个汽车结构的一个特点:
trait Car {
def start(): Unit
val canStart(fuel: Double): Boolean
val fuelInLitr: Int
val carId: Int
}现在,在start()方法中,我想使用一些api服务,它将根据它的id为我提供一个汽车密钥,这样我就不能启动汽车了。
所以我有这个CarApiService
class CarApiService (wsClient: WSClient, configuration: Configuration) {
implicit val formats: Formats = DefaultFormats
def getCarkey(carId: String): Future[Option[CarKey]] = {
val carInfoServiceApi = s"${configuration.get[String]("carsdb.carsInfo")}?carId=$carId"
wsClient.url(carInfoServiceApi).withHttpHeaders(("Content-Type", "application/json")).get.map { response =>
response.status match {
case Status.OK => Some(parse(response.body).extract[CarKey])
case Status.NO_CONTENT => None
case _ => throw new Exception(s"carsdb failed to perform operation with status: ${response.status}, and body: ${response.body}")
}
}
}
}我希望能够在我的汽车对象中使用getCarkey(),所以我创建了一个CarsApiServicesModule,它允许我访问carApiService,我可以使用它的方法:
trait CarsApiServicesModule {
/// this supply the carApiService its confuguration dependancy
lazy val configuration: Config = ConfigFactory.load()
lazy val conf: Configuration = wire[Configuration]
/// this supply the carApiService its WSClient dependancy
lazy val wsc: WSClient = wire[WSClient]
lazy val carApiService: CarApiService = wire[CarApiService]
}现在,我想用这种方式在我的汽车对象中添加这个特性:
object Porsche extends Car with CarsApiServicesModule {
// here I want to use myApiService
// for example: carApiService.getCarkey(carId)...
}但是,在编译这个时,我会得到以下错误:

有人知道这是怎么回事吗?
而且,这种设计有意义吗?
发布于 2017-07-10 16:49:38
您需要记住,wire只是一个帮助宏,它试图生成新的实例创建代码:实际上,它非常愚蠢。在这里,它将尝试创建一个新的WSClient实例。
但是,并不是所有的对象都可以使用简单的new调用来实例化--有时需要调用“工厂”方法。
在本例中,如果您查看基于GitHub的自述,您将看到要实例化WSClient,需要通过StandaloneAhcWSClient()对象创建它。
因此,在这种情况下,wire不会对您有所帮助-您只需手工编写初始化代码即可。幸运的是它不太大。
https://stackoverflow.com/questions/44997710
复制相似问题