【问题标题】:scala: Polymorphic method with HashMap argumentscala:带有 HashMap 参数的多态方法
【发布时间】:2018-09-22 16:20:05
【问题描述】:

正如下面的(不起作用的)代码所示,我想获取任何哈希图并转换为电子表格格式。

  def printHashMapToCsv[T](m:Map[T,T],name:String, path:String): Unit =
  {
    Spreadsheet.initCsvSpreadsheet(name,path)
    m.foreach
    {
      e=> Spreadsheet.addCell(IDGenerator.getInstance().nextID(),e._1.toString,e._2.toString)
    }
    Spreadsheet.printCsvFinal()
  }

上面的代码可以编译,但是当我尝试使用下面的代码调用该方法时,我得到了一个编译方法:

def mapOut(): Unit =
  {
    try{

      val m:mutable.HashMap[Int,String]=new mutable.HashMap[Int,String]()
      m.put(1,"sssss")
      m.put(2,"ghfd")
      m.put(3,"dfsa")
      m.put(4,"fhjgsdf")
      printHashMapToCsv(m,"mapout",s"${new File(".").getAbsolutePath}${File.separator}unitTestOutput")

    }

编译错误:

错误:类型不匹配; [信息] 发现: scala.collection.mutable.HashMap[Int,String] [INFO] 需要: 地图[?,?]

任何建议将不胜感激

【问题讨论】:

  • 您的 printHashMapToCsv[T] 方法需要 Map[T, T](即相同类型的键和值),而您正在为其提供 mutable.HashMap[Int, String]
  • 知道了,这解释了错误

标签: scala generics


【解决方案1】:

您似乎只将一个类型参数 T 传递给 printHashMapToCsv 方法,并使其需要一个 Map[T, T] :

def printHashMapToCsv[T](m:Map[T,T], name:String, path:String)

但是,你给它一个 Map[Int, String],所以有两种不同的类型:

val m:mutable.HashMap[Int,String]=new mutable.HashMap[Int,String]()
printHashMapToCsv(m,"mapout",s"${new File(".").getAbsolutePath}${File.separator}unitTestOutput")

我想传递 2 种类型给它,这个方法定义应该可以解决问题:

def printHashMapToCsv[T, U](m:Map[T, U], name:String, path:String)

但是,如果您知道您传递的类型之一将始终相同(例如 Int),则应仅保留一个类型参数并明确要求它,如下所示:

def printHashMapToCsv[T](m:Map[Int, T], name:String, path:String)

希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    • 2012-11-25
    相关资源
    最近更新 更多