【问题标题】:Understanding Scala default argument message理解 Scala 默认参数消息
【发布时间】:2018-11-22 11:19:20
【问题描述】:

我正在玩一些 Scala 代码,但遇到了一条我不太理解的错误消息。下面是我的代码

val ignoredIds = Array("one", "two", "three")


def csNotify(x : Any): String = {

  case org: String if !ignoredIds.contains(x) =>
    println( s" $x  should not be here")
    "one"
  case org : String if ignoredIds.contains(x) =>
    println(s"$x should be here")
    "two"
}

csNotify("four")

控制台输出是我必须知道默认函数的参数。错误点似乎指向“ String = ”。为什么会这样?该函数应该检查这两种情况并返回一个字符串?

【问题讨论】:

    标签: scala methods


    【解决方案1】:

    您的案例没有找到可以检查您的块的匹配项,并且您错过了匹配块:

    val ignoredIds = Array("one", "two", "three")
    
    
    def csNotify(x : Any): String =  x  match {
    
     case org: String if !ignoredIds.contains(x) =>
    println( s" $x  should not be here")
    "one"
     case org : String if ignoredIds.contains(x) =>
    println(s"$x should be here")
    "two"
    }
    
    csNotify("four")
    

    所以基本上当你在方法中传递x 时,你也必须给它匹配。

    【讨论】:

      【解决方案2】:

      Amit Prasad 的回答已经说明了如何修复它,但要解释错误消息:

      {
      
        case org: String if !ignoredIds.contains(x) =>
          println( s" $x  should not be here")
          "one"
        case org : String if ignoredIds.contains(x) =>
          println(s"$x should be here")
          "two"
      }
      

      它自己(前面没有... match)是a pattern-matching anonymous function,它只能在编译器从上下文中知道参数类型的情况下使用,即预期类型必须是PartialFunction[Something, SomethingElse]或单一抽象-方法类型(包括Something => SomethingElse)。

      这里预期的类型是String,它不是这两个,所以编译器抱怨不知道参数类型是什么。

      【讨论】:

        【解决方案3】:

        您需要在此处使用match 关键字来使用案例。您可能会为某些值使用模式匹配。所以在你的函数中使用以下代码:

        x  match {
          case org: String if !ignoredIds.contains(x) => ???
          case org : String if ignoredIds.contains(x) => ???
        }
        

        此外,您应该考虑再添加一种默认情况。如您所知,函数def csNotify(x: Any): String 的参数x 是any 类型。所以除了String 之外的任何东西也可以在这里传递,比如IntBoolean 或任何自定义类型。在这种情况下,代码将因匹配错误而中断。

        还会有一个编译器警告说match is not exhaustive,因为当前代码没有处理参数x 类型Any 的所有可能值。

        但是,如果您在模式匹配中添加一个默认情况,则前两种情况(意外类型或值)未处理的所有情况都将转到默认情况。这样代码会更加健壮:

        def csNotify(x : Any): String =  x  match {
          case org: String if !ignoredIds.contains(org) => ???
          case org : String if ignoredIds.contains(org) => ???
          case org => s"unwanted value: $org" // or any default value
        }
        

        注意:请将??? 替换为您想要的代码。 :)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-05-26
          • 2017-03-07
          • 2013-10-13
          • 1970-01-01
          • 2011-08-06
          • 2012-08-06
          • 1970-01-01
          相关资源
          最近更新 更多