这个下划线的含义是什么?

时间:2016-11-01 08:12:40

标签: scala akka-http

我正在阅读akka-http源代码,这里是akka.http.scaladsl.server.directives.RouteDirectives的源代码,以complete方法为例,任何人都可以告诉{{1}中下划线的含义是什么}}?

StandardRoute(_.complete(m))

1 个答案:

答案 0 :(得分:2)

StandardRoute(_.complete(m))相当于StandardRoute(x => x.complete(m))

这里的下划线是指x。如果你想知道scala中下划线的用例。请检查this link (Uses of underscore in Scala)

以下是akka http库的代码

object StandardRoute {
  def apply(route: Route): StandardRoute = route match {
    case x: StandardRoute ⇒ x
    case x                ⇒ new StandardRoute { def apply(ctx: RequestContext) = x(ctx) }
  }

  /**
   * Converts the StandardRoute into a directive that never passes the request to its inner route
   * (and always returns its underlying route).
   */
  implicit def toDirective[L: Tuple](route: StandardRoute): Directive[L] =
    Directive[L] { _ ⇒ route }
}

路线只不过是功能

type Route = RequestContext ⇒ Future[RouteResult]

<强>解释

考虑这个对象编号。该对象的apply方法具有一个功能。现在看看如何使用这个Number对象。

object Number {
 def apply(f: String => Int): Int = {
  f("123") 
 }
}

用法:

Number(_.toInt)

Number(x => x.toInt)

Scala REPL

scala> object Number {
     |      def apply(f: String => Int): Int = {
     |       f("123") 
     |      }
     |     }
defined object Number

scala> Number(_.toInt)
res0: Int = 123

scala> Number(x => x.toInt)
res1: Int = 123