【问题标题】:Why do I get "pattern type is incompatible with expected type"?为什么我得到“模式类型与预期类型不兼容”?
【发布时间】:2010-06-15 22:48:51
【问题描述】:

我在 Scala 代码中遇到了一个我自己无法解决的错误(我是 Scala 的新手)。 我有以下代码:

def myFunction(list: List[Any]): String = {
  var strItems : String = "";
  list.foreach(item => {
    strItems += item match {
      case x:JsonSerializable => x.toJson()
      case y:String => ("\"" + y + "\"")
      case _ => item.toString
    }
    if(item != list.last)
      strItems +=  ",";
  })
  strItems;
}

我得到的错误是:

错误:模式类型与预期类型不兼容; 发现:字符串 要求:单位 case y:String => ("\"" + y + "\"")

知道为什么吗?

PS:有没有更高效的方式来编写 myFunction

【问题讨论】:

    标签: scala match


    【解决方案1】:

    就原始问题而言,代码无法编译,因为它需要在匹配项周围加上括号,即。 strItems += (item match { ... })

    一种更“实用”的写法可能是这样的:

    def myFunction(list:List[Any]):String = {
      val strings:List[String] = list.map{
        case x:JsonSerializable => x.toJson()
        case y:String => ("\"" + y + "\"")
        case z => z.toString
      }
      strings.mkString(",")
    }
    

    您可能会使用视图使其变得懒惰并更“高效”,尽管我不知道这是否会将两个底层循环(mapmkString)组合成一个单次遍历。

    【讨论】:

    • 使用view 会将mapmkString 变成一次遍历。
    【解决方案2】:

    这是您的代码的一种形式,可以编译(没有任何JsonSerializable 的定义)(在 Scala 2.8 中)以及更简洁的公式(也恰好是无点的):

    object Javier01 {
      def
      javFunc(list: List[Any]): String = {
        val strItems = new StringBuilder()
    
        list.foreach { item =>
          strItems.append ( item match {
    //      case x: JsonSerializable => x.toJson()
            case y: String => "\"" + y + "\""
            case _ => item.toString
          } )
    
          if (item != list.last)
            strItems.append(",")
        }
        strItems.toString
      }
    
      def
      rrsFunc(anys: List[Any]): String =
        anys map {
    //    case x: JsonSerializable => x.toJson()
          case s: String => "\"" + s + "\""
          case x => x.toString
        } mkString ","
    
    
      def
      main(args: Array[String]): Unit = {
        val stuff = List(true, 1, 123.456, "boo!")
    
        printf("        stuff : %s%njavFunc(stuff): %s%nrrsFunc(stuff): %s%n%n",
               stuff, javFunc(stuff), rrsFunc(stuff))
      }
    }
    

    运行的输出是:

    % scala Javier01
            stuff : List(true, 1, 123.456, boo!)
    javFunc(stuff): true,1,123.456,"boo!"
    rrsFunc(stuff): true,1,123.456,"boo!"
    

    【讨论】:

      猜你喜欢
      • 2018-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-24
      • 1970-01-01
      相关资源
      最近更新 更多