2

如何将大小写与无形变量匹配?

假设我有以下类型的变量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到字符串对,这样我就不必在单独的语句中执行了吗?

4

1 回答 1

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方法的替代语法:而不是:Tuple2a :: 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 }
于 2013-07-24T05:47:14.747 回答