我有一個密封特征的模式匹配,它需要一個案例類中的兩個,如下所示:
expressions.head match {
case SingleValueExpression(value,_operator,_ignoreCase) => filter FromScala(
SingleValueExpression(value,_operator,_ignoreCase)
).transform(ToJson.string)
case MultipleValueExpression(value,_operator,_apply,_instances) => filter FromScala(
MultipleValueExpression(value,_operator,_apply,_instances)
).transform(ToJson.string)
}
您可以看到,即使在解碼案例類之后,我也會在下一步中重新創建案例類:
case MultipleValueExpression(value,_operator,_apply,_instances) => MultipleValueExpression(value,_operator,_apply,_instances)
有沒有一種方法可以匹配模式,這樣我就可以檢查實體是否屬于該案例類,然后按原樣使用該值,而不是解構它并重新創建相同的案例類?
uj5u.com熱心網友回復:
要僅檢查模式匹配中的型別,請使用:,如下所示:
expressions.head match {
case sve: SingleValueExpression => filter FromScala(sve).transform(ToJson.string)
case mve: MultipleValueExpression => filter FromScala(mve).transform(ToJson.string)
}
你甚至可以有類似的東西
val fromScala =
expressions.head match {
case sve: SingleValueExpression => FromScala(sve)
case mve: MultipleValueExpression => FromScala(mve)
}
filters fromScala.transform(ToJson.string)
您也可以同時使用@提取和系結case(例如,您希望基于 a 的組件進行匹配case class但保存整體匹配):
case sve @ SingleValueExpression(value, _, _) if somePredicate(value) =>
// sve is the overall SingleValueExpression, and value is also available in this branch
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/533370.html
標籤:斯卡拉模式匹配
