2016-03-05 97 views
1

应用在Scala中,我有一个类型的方法:地图不正确

HashMap[String, String] 

而且这个变量:

var bestMatch = new HashMap[String, (String, Int)] 

在方法的结束,我想返回该值:

bestMatch.map((x, (y, count)) => (x, y)) 

不过,我得到的错误:

Cannot resolve reference map with such signature 

为什么我错误地应用它?

回答

3

应该是这样的:

bestMatch.map(tuple => (tuple._1, tuple._2._1)) 

你不能只是把(String,Int)元组的两个参数作为lambda函数的参数。你需要使用这个元组作为一个元组。如果你写出你的参数类型,它可能会变得更清晰。

bestMatch.map((tuple: (String,(String,Int))) => (tuple._1, tuple._2._1)) 

另外,在你的情况下,可以更好地使用mapValues因为你没有做你的关键事情。那么你可以使用这个:

bestMatch.mapValues(tuple => tuple._1) 

如果你问我,这更可读。你甚至可以更进一步说:

bestMatch.mapValues(_._1) 
3

你可以写

bestMatch map {case (x, (y, count)) => (x, y)}