scala - 为什么在案例类的理解和模式匹配中出现编译错误

标签 scala

谁能知道为什么下面的代码不能通过编译?我只是不知道为什么会发生类型不匹配。

输出应如下所示:

List(Book, DVD, MP3)

我的代码:
package library3 {

  abstract class Item() {
    def use(): Unit
  }

  // match on Items.

  case class Book (val title: String) extends Item
  case class DVD (val title: String) extends Item
  case class MP3 (val title: String) extends Item
}

object Ch3_2 {

  import library3._

  def main( args:Array[String] ) = {
    val items = List( new Book( "The Hobbit" ),
              new DVD( "Black Adder Goes Forth" ),
              new MP3( "Watership Down" )
            )

    println( classifyItems( items ) )
  }

  def classifyItems( items:List[Item] ): List[String] = {

    // Use a for comprehension and pattern matching to take a list of
    // items and return a list of types of items.

    for (item <- items) { // <=== type mismatch;
        item match {
            case b: Book => println("Book")
            case d: DVD => println("DVD")
            case m: MP3 => println("MP3")
        }
    }

  }

}

错误信息:
error: type mismatch;
found   : Unit
 required: List[String]
    for (item <- items) {
              ^
one error found

最佳答案

这是您的代码的工作版本:

abstract class Item

case class Book (title: String) extends Item
case class DVD (title: String) extends Item
case class MP3 (title: String) extends Item

val items = List( 
  Book( "The Hobbit" ),
  DVD( "Black Adder Goes Forth" ),
  MP3( "Watership Down" )
)

def classifyItems(items:List[Item]): List[String] = 
  for (item <- items) yield
    item match {
      case b: Book => "Book"
      case d: DVD => "DVD"
      case m: MP3 => "MP3"
      case _ => "else"
    }

验证它确实有效:
scala> classifyItems(items)
res2: List[String] = List(Book, DVD, MP3)    

几点说明:
  • 使用案例类时,您不必使用 new
  • 您必须使用 yield for 之后的声明陈述。
  • 如果您不想在 match 中使用默认大小写, 你必须使用 sealed traitsealed class
  • 更多信息 for Scala 中的语句:http://www.scala-lang.org/node/111
  • 关于scala - 为什么在案例类的理解和模式匹配中出现编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12761611/

    相关文章:

    arrays - 直观地解释为什么 `List` 是协变的,而 `Array` 是不变的?

    scala - 在 Spark 中保存文件

    scala - 使用 map 元素作为方法参数

    scala - 是否有针对 scala googleprotobuf "bindings"的社区努力?

    scala - 玩框架WSClient测试

    scala - 传递选择的选定值以形成操作

    java - play 框架不是有效的 id

    Java 或 Scala maven 使用 CLASSPATH 安装 jar

    scala - select后的spark sql where子句

    scala - 类型类接口(interface)的DataSet/DataStream