1

假设我的项目中有一堆汽车对象,例如:

object Porsche extends Car {
   override def start() {...}
   override def canStart(fuelInLitr: Int) = fuelInLitr > 5

   override val fuelInLitr = 45
   override val carId = 1234567
}

我正在扩展 Car 这只是设置汽车结构的一个特征:

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)...
}

但是当编译这个我得到这个错误:

在此处输入图像描述

有谁知道是什么问题?

还有,这样的设计有意义吗?

4

1 回答 1

1

您需要记住,这wire只是一个尝试生成新实例创建代码的辅助宏:事实上,它非常愚蠢。在这里,它会尝试创建一个新的WSClient.

但是,并非所有对象都可以使用简单的new调用来实例化 - 有时您需要调用“工厂”方法。

在这种情况下,如果您查看GitHub 上的自述文件,您会看到要实例化WSClient,您需要通过StandaloneAhcWSClient()对象创建它。

所以在这种情况下,wire不会帮助你 - 你需要简单地手动编写初始化代码。幸运的是它不是太大。

于 2017-07-10T16:49:38.300 回答