简体   繁体   中英

Error type mismatch while using generics in scala

Getting errors while using generics in scala:

import scala.collection.mutable

class test {
  val car = mutable.Map.emprty[String, (Int,Int)]
  read[String, (Int,Int)] ("file.txt",car)
  def read[T,V] (fileName:String, mapName: mutable.Map[T,V]) {
    mapName("abc") = (1,2)
  }

Error:

   error: type mismatch
   found: java.lang.String("abc")
   required: T

Your code isn't really generic, because inside read function body, you are assuming T and V to be String and (Int, Int) . The generic parameters are bounds on your method signature and they are only useful when types of arguments or return types relate in some way to each other.

I think with your code will be perfectly fine to use concrete types in the read function signature:

def read(fileName: String, mapName: mutable.Map[String, (Int, Int)]) {
  mapName("abc") = (1,2)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM