大家好,我是scala的新手,我正在尝试从函数返回一个map(Map[String,USER]),但是遇到了类型不匹配错误

wydwbb8l  于 2022-12-13  发布在  Scala
关注(0)|答案(1)|浏览(151)

这是我的userRepository特征

import scala.collection.mutable.Map

trait userRepository {
  def addUser(id: String, user:USER):Map[String,USER]
  def removeUser(id: String):Map[String,USER]
  def getUser(id: String):Map[String,USER]
}

下面是我的userRepositoryImpl类

import scala.collection.mutable.Map

class userRepositoryImpl extends userRepository {
  val userMap = Map.empty[String,USER]

  override def addUser(id: String, user: USER): Map[String,USER] = {
    userMap.put(id, user)
  }

  override def removeUser(id: String): Map[String,USER] = {
      userMap.remove(id)
    }

  override def getUser(id: String): Map[String,USER] = {
    userMap.find(_._2.id == id)
  }
}

下面是我的USER类

case class USER(id: String, firstName: String, lastName: String, email: String, address: String, gender: String)

埃罗

type mismatch;
 found   : Option[USER]
 required: scala.collection.mutable.Map[String,USER]
    userMap.put(id, user)

为什么我会得到这个错误?可以任何朋友解释的原因?

0x6upsns

0x6upsns1#

谢谢,通过返回“userMap”解决。
例如,

override def removeUser(id: String): Map[String, USER] = {
    userMap.remove(id)
    userMap
  }

这是不匹配错误

相关问题