【问题标题】:scala: return value for a method and end the method prematurelyscala:方法的返回值并提前结束该方法
【发布时间】:2012-09-28 00:44:57
【问题描述】:

我刚刚开始使用 Scala,所以请耐心等待。

我正在编写一个基于在给定列表中找到的“*”数量返回布尔值的方法。

def stars(n: Int, chars: List[Char]): Boolean = {
  var count = 0
  chars.foreach{ letter =>
    if (letter == "*") {
      count += 1
    }
    if (count == n) {
      return true
    }

  }
  false
}                                               //> stars: (n: Int, chars: List[Char])Boolean

stars(5, "******".toList)                       //> res12: Boolean = false

这应该返回 true。因为它应该在计数变为 5 时提前结束,它等于 n

我做错了什么?

Scala 不允许使用return 语句过早结束方法吗?

【问题讨论】:

    标签: scala


    【解决方案1】:

    if (letter == "*") 中,您将 char 与 string 进行比较,因此不断得到错误,并且您的 count += 1 永远不会被评估
    你必须改写if (letter == '*')

    实际上,更惯用的代码是:

    def stars(n: Int, chars: List[Char]): Boolean = {
      n == chars.count(c => c == '*')
    }
    

    【讨论】:

    • 您的惯用代码不会提前终止。 chars.iterator.filter(_ == '*').take(5).length == 5 会。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2020-09-28
    • 2021-11-18
    • 1970-01-01
    • 2015-01-03
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多