如何将案例与无形变量匹配?
假设我有以下类型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对,这样我就不必在单独的语句中进行操作了吗?
答案 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 }