Home > other >  What is the error "error: type mismatch;" in scala?
What is the error "error: type mismatch;" in scala?

Time:10-31

import java.time.LocalDate
object Main extends App{
    case class Score(
      name:    String,    
      english: Int,       
      math:    Int,       
      science: Int,       
      date:    LocalDate  
    )
    val scoreOfAlice   = Score(name = "Alice",   english = 77,  math = 74, science = 26, date = LocalDate.of(2020, 1, 30))
    val scoreOfBob     = Score(name = "Bob",     english = 100, math = 74, science = 14, date = LocalDate.of(2020, 1, 26))
    val scoreOfCharlie = Score(name = "Charlie", english = 100, math = 74, science = 99, date = LocalDate.of(2020, 1, 26))
    val scoreOfDave    = Score(name = "Dave",    english = 50,  math = 81, science = 88, date = LocalDate.of(2020, 1, 30))
    val scores: Seq[Score] = Seq(scoreOfAlice, scoreOfBob, scoreOfCharlie, scoreOfDave)
    println(getDateNameScoreMap(scores)(LocalDate.of(2020, 1, 30))("Alice"))
    def getDateNameScoreMap(scoreSeq: Seq[Score]): Map[LocalDate, Map[String, Int]] = scores.groupMap(score => score.date)(score=>Map(score.name -> (score.english score.math score.science)))
}

I would like to implement a function that maps the examination date to a map of student names and the total scores of the three subjects on that date, and if there are multiple scores for the same student on the same date, the function returns the one with the highest total score. However, here is the function

found :scala.collection.immutable.Map[java.time.LocalDate,Seq[scala.collection.immutable.Map[String,Int]]]]

"required: Map[java.time.LocalDate,Map[String,Int]]".

How can I resolve this?

CodePudding user response:

The error means what it says: The type of the variable and the type of the value being assigned to the variable don't match. It even tells you what the two types are!

The actual problem is that groupMap isn't returning the type you think it should. The values in the resulting Map are a Seq of Maps rather than a single Map with all the results.

You can use groupMapReduce to convert the List to a single Map by concatenation the Maps using :

scores
  .groupMapReduce(_.date)
    (score=>Map(score.name -> (score.english score.math score.science)))
    (_    _)
  • Related