You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 for loop doesn't pass the matching domain back as the function's return value. Even though you evaluate i inside the if block, 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 where c.contains(domain) is true, wrapped in a Some(domain). If no matches exist, it returns None.
  • .getOrElse("N/A") handles the Option result: 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 println outside the if block.

Test Cases

  • Calling f("www.google.com/1234") will print comparing www.google.com/1234 with google.com and return "google.com".
  • Calling f("bloomberg.com/example") will return "N/A" with no print output.

内容的提问来源于stack exchange,提问作者Riyan Mohammed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:50:42