Scala数组元素匹配函数问题:实现匹配元素或N/A返回逻辑
Fixing the Scala Domain Matching Function
Let's sort out this function so it behaves exactly as you want: returning the first matching domain from your list, or "N/A" if none are found.
What's Wrong with the Original Code?
The original implementation has two critical issues that stop it from working correctly:
- The
forloop doesn't pass the matching domain back as the function's return value. Even though you evaluateiinside theifblock, that value is just discarded — it doesn't override the final"N/A"return. - The function unconditionally returns
"N/A"at the end, no matter if a valid match was found earlier.
The Corrected Implementation
We can use Scala's built-in collection methods to make this clean and functional:
def f(c: String): String = { val domains = "google.com|yahoo.com|gmail.com|mail.com".split("\\|") domains.find(domain => { val isMatch = c.contains(domain) if (isMatch) { println(s"comparing $c with $domain") } isMatch }).getOrElse("N/A") }
How This Works
domains.find(...)iterates through each domain in the list and returns the first one wherec.contains(domain)istrue, wrapped in aSome(domain). If no matches exist, it returnsNone..getOrElse("N/A")handles theOptionresult: if there's a match, it extracts the domain string; if not, it falls back to returning"N/A".- The print statement only runs when a match is found, just like your original code intended. If you wanted to print every comparison (even non-matches), you could move the
printlnoutside theifblock.
Test Cases
- Calling
f("www.google.com/1234")will printcomparing www.google.com/1234 with google.comand return"google.com". - Calling
f("bloomberg.com/example")will return"N/A"with no print output.
内容的提问来源于stack exchange,提问作者Riyan Mohammed
相关产品推荐
相关产品推荐

