播放Scala-找到Future [String],但出现预期的String错误

时间:2018-09-04 06:14:21

标签: scala playframework future

我是Play Scala的新手。在下面的代码段中,我试图使用它来公开API。失败并显示以下错误。

type mismatch;
 found   : scala.concurrent.Future[String]
 required: String

API来源:

def getStrategy(date: String) = Action.async {
    val currentDate:String = toString(DateTime.now.minusDays(1))
    getDecision(date, currentDate).map(lastError => Ok("No Strategy found:%s".format(lastError)))
  }

  def getDecision(reqestedDate:String, currentDate:String): Future[String] = {
    getForecastPrice(reqestedDate).map(forecastPrice =>
      getCurrentPrice(currentDate).map(currentPrice => 
        getCall(currentPrice, forecastPrice)
      )
    )
  }

  def getForecastPrice(requestedDate:String): Future[Option[Double]] = {
    predictionRepo.getPrediction(requestedDate).map( maybePrediction =>
      maybePrediction.map ( fPrice => fPrice.price )
    )
  }

  def getCurrentPrice(currentDate:String): Future[Option[Double]] = {
    priceRepo.getPrice(currentDate).map ( maybePrice =>
      maybePrice.map ( cPrice => cPrice.price )
    )
  }

  def getCall(currentPrice:Option[Double], forcastPrice:Option[Double]): String = {
    var decision = ""
    println("currentPrice:" + currentPrice)
    println("forcastPrice:" + forcastPrice)

    if(currentPrice.isDefined && forcastPrice.isDefined) {
      var currentPriceValue = currentPrice.get.toDouble
      var forcastPriceValue = forcastPrice.get.toDouble

      if((currentPriceValue*5/100) < (currentPriceValue - forcastPriceValue)) {
        decision = "BUY"
      } else if((currentPriceValue*5/100) > (currentPriceValue - forcastPriceValue)) {
        decision = "SELL"
      } else {
        decision = "HOLD"
      }
    }
    return decision
  }

上述代码中的错误在以下位置显示。

getCurrentPrice(currentDate).map(currentPrice => 

您能帮我找到此问题的原因吗?

2 个答案:

答案 0 :(得分:2)

您可以将map中的第一个getDecision更改为flatMap

def getDecision(reqestedDate:String, currentDate:String): Future[String] = {
    getForecastPrice(reqestedDate).flatMap(forecastPrice =>
      getCurrentPrice(currentDate).map(currentPrice => 
        getCall(currentPrice, forecastPrice)
      )
    )
  }

使用当前代码,结果类型将为Future[Future[String]]

答案 1 :(得分:2)

您可以使用它来理解而不是在另一个地图中使用一个地图。示例代码就是这样。

for(
getForecastPriceResult <- getForecastPrice(requestedDate);
getCurrentPriceResult <- getCurrentPrice(currentDate)
) yield(getCall(getForecastPriceResult,getCurrentPriceResult))