简体   繁体   English

在Scala中使用泛型时发生错误类型不匹配

[英]Error type mismatch while using generics in scala

Getting errors while using generics in scala: 在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) . 您的代码不是真正的通用代码,因为在read函数体内,您假设TVString(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: 我认为您的代码在read函数签名中使用具体类型将是完美的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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