次のコードがコンパイルに合格できない理由を誰かが知っていますか?なぜ型の不一致が発生するのかわかりません。
出力は次のようになります。
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