Reputation: 51
I am new to Play Scala. Below code snippet I am trying to use to expose an API. Its failing with the below error.
type mismatch;
found : scala.concurrent.Future[String]
required: String
API source:
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
}
Error in the above code is shwon at the below location.
getCurrentPrice(currentDate).map(currentPrice =>
Could you please help me to find the reason for this issue?
Upvotes: 0
Views: 463
Reputation: 664
You can use for comprehension rather than using a map inside another map. The sample code would be something like this.
for(
getForecastPriceResult <- getForecastPrice(requestedDate);
getCurrentPriceResult <- getCurrentPrice(currentDate)
) yield(getCall(getForecastPriceResult,getCurrentPriceResult))
Upvotes: 2
Reputation: 7544
Can you change the first map
in getDecision
to flatMap
:
def getDecision(reqestedDate:String, currentDate:String): Future[String] = {
getForecastPrice(reqestedDate).flatMap(forecastPrice =>
getCurrentPrice(currentDate).map(currentPrice =>
getCall(currentPrice, forecastPrice)
)
)
}
With the current code the result type would Future[Future[String]]
Upvotes: 2