[英]Scala: string pattern matching
The below code takes the first two character of string and check if pattern is "de" or None
it returns None else it returns the Test("Found")
下面的代码采用字符串的前两个字符,并检查pattern是否为
"de" or None
否则返回None,否则返回Test("Found")
val s =Option("abc")
val t = s.map(_.take(2))
case class Test(id:String)
t match {
case Some("de") => None
case None => None
case _ => Test("Found")
}
Can anyone suggest a efficient solution for case matching 任何人都可以提出一个有效的案例匹配解决方案
I think I get what you're asking so let me try this: 我想我知道您的要求,所以让我尝试一下:
val condition = Option("abc").exists(_.toLower.take(2) == "de")
val output: Any = if(condition) Test("found") else None
The first portion returns false
if the Option
is None
. 如果
Option
为None
则第一部分返回false
。 It also returns false
if the first two letters of the string are "de"
in a case insensitive way. 它还返回
false
,如果字符串的前两个字母是"de"
在不区分大小写的方式。
The second portion returns either a None
or a Test
object. 第二部分返回
None
或Test
对象。 However, I want to point out that this results in an Any
. 但是,我想指出的是,这会导致
Any
。 Did you mean for it to return a Option[Test]
type instead? 您是说要它返回
Option[Test]
类型吗?
I assume, you meant Some(Test("Found"))
in the last line of your snippet, judging from your comment to the other answer. 我认为,从您的评论到另一个答案,您的意思是在代码段的最后一行中输入
Some(Test("Found"))
。 If so, this is what you are looking for: 如果是这样,这就是您要寻找的:
t.filterNot(_.take(2) == "de").map(_ => Test("Found"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.