为什么我会收到“模式类型与预期类型不兼容”?

发布于 2024-09-05 15:51:04 字数 561 浏览 9 评论 0原文

我在 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;
}

我收到的错误是:

错误:模式类型与预期类型不兼容; 发现:字符串 必填:单位 情况 y:字符串 => ("\"" + y + "\"")

知道为什么吗?

PS:是否有更高效的方法来编码 myFunction

I came across with an error on my Scala code that I cannot solve by myself (I am new at Scala).
I have the following code:

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;
}

The error I am getting is:

error: pattern type is incompatible with expected type;
found : String
required: Unit
case y:String => ("\"" + y + "\"")

Any idea why?

PS: is there a more performant way to code myFunction

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

临走之时 2024-09-12 15:51:05

就原始问题而言,代码无法编译,因为它需要在匹配项周围加上括号,即。 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) 合并为一个遍历。

In terms of the original question, the code doesn't compile because it requires parentheses around the match, ie. strItems += (item match { ... })

A more "functional" way of writing this could be something along the lines of:

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(",")
}

You could probably use a view to make it lazy and more "performant", although I don't know off the top of my head if that would combine the two underlying loops (map & mkString) into a single traversal.

终止放荡 2024-09-12 15:51:05

下面是可以编译的代码形式(在 Scala 2.8 中没有任何 JsonSerialized 的定义)以及更简洁的公式(也恰好是无点的):

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!"

Here's a form of your code that compiles (w/o any definition for JsonSerializable) (in Scala 2.8) along with a more succinct formulation (that also happens to be point-free):

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))
  }
}

The output from running this is:

% scala Javier01
        stuff : List(true, 1, 123.456, boo!)
javFunc(stuff): true,1,123.456,"boo!"
rrsFunc(stuff): true,1,123.456,"boo!"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文