如何将案例与无形变量匹配?

时间:2013-07-24 04:54:01

标签: scala shapeless

如何将案例与无形变量匹配?

假设我有以下类型shapeless.::[String,shapeless.::[String,shapeless.HNil]]

的变量

目前我必须这样做

authHeaders.hrequire(shape_value => {
    val (client_id, client_secret) = value.tupled
    isAuthorized(client_id, client_secret)
  }
  )

我可以以某种方式将String :: String :: HNil解除为String对,这样我就不必在单独的语句中进行操作了吗?

1 个答案:

答案 0 :(得分:4)

对象unapply中有方法shapeless.::

def unapply[H, T <: HList](x: H :: T): Option[(H, T)]

所以你可以像这样匹配HList

scala> val ::(a, ::(b, HNil)) = "1" :: "x" :: HNil
a: String = 1
b: String = x

或使用unapply结果的Tuple2方法的替代语法:a :: b而不是::(a, b)

scala> val a :: b :: HNil = "1" :: "x" :: HNil
a: String = 1
b: String = x

scala> "1" :: "x" :: HNil match {
     |   case a :: b :: HNil => s"$a :: $b :: HNil"
     | }
res0: String = 1 :: x :: HNil

在你的情况下:

authHeaders.hrequire{
  case client_id :: client_secret :: HNil => isAuthorized(client_id, client_secret)
}

<强>替代

您可以使用tupled方法将N个参数的函数转换为单个TupleN参数的函数。

功能:

val isAuthorized: (String, String) => Boolean = ???
authHeaders.hrequire{ isAuthorized tupled _.tupled }

方法:

def isAuthorized(s1: String, s2: String): Boolean = ???
authHeaders.hrequire{ (isAuthorized _) tupled _.tupled }