Why a compilation error in to understand and map patterns for case classes

Can anyone know why the following code cannot pass compilation? I just don't know why type mismatch occurs.

The result should look like this:

List(Book, DVD, MP3) 

My code is:

 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 message:

 error: type mismatch; found : Unit required: List[String] for (item <- items) { ^ one error found 
+4
source share
1 answer

Here is the working version of your code:

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

Verifying that it really works:

 scala> classifyItems(items) res2: List[String] = List(Book, DVD, MP3) 

A few notes:

  • When using the case class you do not need to use new
  • You must use the yield after the for statement.
  • If you do not want to use the default case in match , you need to use the sealed trait or sealed class
  • For more information on the Scala for statement: http://www.scala-lang.org/node/111
+3
source

Source: https://habr.com/ru/post/1438173/


All Articles