Scala函数返回对象类型

时间:2016-11-16 09:10:49

标签: scala

我的定义如下:

sealed trait ServiceResponse
  case object OK extends ServiceResponse
  case object SHIT extends ServiceResponse

  private def remoteService(waitTime: FiniteDuration): ServiceResponse = {
    val awaitable: Future[Ok.type] = Future.successful {
      Thread.sleep(waitTime.toMillis)
      OK
    }
    Await.ready(awaitable, waitTime)
  }

remoteService函数投诉说它期待一个类型。那为什么这个问题呢?为什么我不能简单地返回一个Object类型?

1 个答案:

答案 0 :(得分:1)

这是因为您需要使用Await.result而不是Await.ready。这有效:

import scala.concurrent._
import scala.concurrent.duration._

sealed trait ServiceResponse {

  case object OK extends ServiceResponse
  case object SHIT extends ServiceResponse

  private def remoteService(waitTime: FiniteDuration): ServiceResponse = {
    val awaitable: Future[OK.type] = Future.successful {
      Thread.sleep(waitTime.toMillis)
      OK
    }
    Await.result(awaitable, waitTime)
  }

}

你也有错字:未来[Ok.Type]应该是Future [OK.type]