加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 为什么在用于案例类的理解和模式匹配中的编译错误

发布时间:2020-12-16 08:48:10 所属栏目:安全 来源:网络整理
导读:谁能知道为什么以下代码无法通过编译?我只是不知道为什么会发生类型不匹配. 输出应如下所示: List(Book,DVD,MP3) 我的代码: package library3 { abstract class Item() { def use(): Unit } // match on Items. case class Book (val title: String) exte
谁能知道为什么以下代码无法通过编译?我只是不知道为什么会发生类型不匹配.

输出应如下所示:

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,MP3)

几点评论:

>使用案例类时,您不必使用新的
>您必须在for语句后使用yield语句.
>如果您不想在比赛中使用默认情况,则必须使用密封特性或密封类
>有关Scala中for语句的更多信息:http://www.scala-lang.org/node/111

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读