开发者

Shorter version of string match in Scala

开发者 https://www.devze.com 2023-02-06 00:43 出处:网络
I have the following code: if (element.matches(\"class Int\")) true else false Is it possible to use a func开发者_开发知识库tion like the *.getOrElse for Sets to have cleaner code?if(condition) tru

I have the following code:

if (element.matches("class Int"))
      true
    else
      false

Is it possible to use a func开发者_开发知识库tion like the *.getOrElse for Sets to have cleaner code?


if(condition) true else false

is equivalent to just condition, so you can remove the if statement in your code and just use

element.matches("class Int")

Also note that your pattern doesn't actually contain any regex operators and String.matches matches the whole string, so the whole thing is equivalent to checking whether element is equal to "class Int". So you don't actually need to use matches at all.


Is it something like this you're thinking about. I don't see how it makes things better unless you have a for()-comprehension and want to stop on a condition:

Some("a".matches("b")).filter(t => t).getOrElse(false)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号