2016-11-01 69 views
1

我正在閱讀akka-http源代碼,這裏是akka.http.scaladsl.server.directives.RouteDirectives的源代碼,以complete方法爲例,任何人都可以告訴StandardRoute(_.complete(m))下劃線的含義是什麼?這個下劃線的含義是什麼?

package akka.http.scaladsl.server 
package directives 

import akka.http.scaladsl.marshalling.ToResponseMarshallable 
import akka.http.scaladsl.model._ 
import StatusCodes._ 

/** 
* @groupname route Route directives 
* @groupprio route 200 
*/ 
trait RouteDirectives { 

    .... 
    .... 

    /** 
    * Completes the request using the given arguments. 
    * 
    * @group route 
    */ 
    def complete(m: ⇒ ToResponseMarshallable): StandardRoute = 
    StandardRoute(_.complete(m)) 
} 

object RouteDirectives extends RouteDirectives { 
    private val _reject = StandardRoute(_.reject()) 
} 

回答

2

StandardRoute(_.complete(m))相當於StandardRoute(x => x.complete(m))

這裏強調指x。如果你想知道scala中下劃線的用例。請檢查this link (Uses of underscore in Scala)

這裏是阿卡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 
+0

不,StandardRoute的適用方法只接受路由實例。 –

+0

@LaurenceGeng路線必須擴展功能 – pamu

+0

@LaurenceGeng'StandardRoute(_。complete(m))'可以用'StandardRoute(x => x.complete(m))替換' – pamu