简体   繁体   中英

Scala Why am I getting a type mismatch with hashmap?

I am getting a type mismatch here? Am I not create a HashMap of key char and value int? Is i some type of iterator instead of a int?

import scala.collection.mutable.HashMap

object Solution {
    def firstUniqChar(s: String): Int = {
        var hashMapName =        HashMap[Char, Int]();
        for (i <- 0 until s.length){
             if (hashMapName.contains(s.charAt(i)) ) return i-1
            else hashMapName = hashMapName + (s.charAt(i), i)
            println(s.charAt(i))
        }
        return -1;
    }
}

In Scala everything is a method call, including what looks like operators.

That means that

hashMapName + (s.charAt(i), i)

is ambiguous to the parser, because it's unclear whether you are using the operator syntax or the method syntax, which would be

hashMapName.+(s.charAt(i), i)

In order to fix the error you have to add an extra pair of parentheses to clarify that you are not trying to invoke a method with two arguments but a method with a one argument, which happens to be a pair

hashMapName + ((s.charAt(i), i))

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