2012-10-06 27 views
4

任何人都可以知道为什么下面的代码不能通过编译?我只是不知道为什么类型不匹配发生。为什么编译错误在理解和模式匹配案例类

输出应该是这样的:

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 

回答

3

这里是你的代码的工作版本:

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使用默认情况下,你必须使用Scala中关于for语句sealed traitsealed class
  • 更多信息:http://www.scala-lang.org/node/111
+0

感谢。我知道你的验证是正确的。但是当我编译时,它不起作用。 ////////// scalac yourcode.scala ///////// yourcode.scala:9:错误:预期类或对象定义 VAL项=列表( ^ yourcode.scala:15:错误:预期类或对象定义 高清classifyItems(项目:列表[项目]):列表[字符串] = ^ 两个错误发现 – user1725406

+0

我测试我的代码在REPL,让你拥有例如:'object Ch3_2 {val items ...; def classifyItems ...}' –

+0

谢谢你,你的代码是完美的,我知道我的错误发生是因为我做了不在派生类中定义use() s与基类Item中的use()一样。 – user1725406