0
fun main() {
    val list = listOf("B", "A", "A", "C", "B", "A")
    print(findfrequency(list))
}

fun <T> findfrequency(list: T): MutableMap<String, Int> {
    val frequencyMap: MutableMap<String, Int> = HashMap()
 
    for (s in list) {
        var count = frequencyMap[s]
        if (count == null) count = 0
        frequencyMap[s] = count + 1
    }
    
    return frequencyMap
}
sidgate
  • 14,650
  • 11
  • 68
  • 119
TheDevTing
  • 11
  • 2

2 Answers2

1

Solution: No need for generic type declaration of the variable list, just add <String> in the function parameter. Here is the final program:

fun main() {
    val list_String = listOf("B", "A", "A", "C", "B", "A")
    println(findfreq(list_String))
}

fun findfreq(list: List<String>): MutableMap<String, Int> {
    val frequencyMap: MutableMap<String, Int> = HashMap()
    
    for(i in list) {
        var count = frequencyMap[i]
        if(count == null) count = 0
        frequencyMap[i] = count + 1
    }
    
    return frequencyMap
}

Playground link

spender
  • 117,338
  • 33
  • 229
  • 351
TheDevTing
  • 11
  • 2
0

When you put a list of strings into a function with type T, its type is unknown at runtime, and you are trying to iterate over this unknown type. Therefore, you must indicate that this object can be used to interact with.

fun main() {
    val list = listOf("B", "A", "A", "C", "B", "A")
    print(findfrequency(list))
}

fun <T : Iterable<String>> findfrequency(list: T): MutableMap<String, Int> {
    val frequencyMap: MutableMap<String, Int> = HashMap()

    for (s in list) {
        var count = frequencyMap[s]
        if (count == null) count = 0
        frequencyMap[s] = count + 1
    }

    return frequencyMap
}

In the example below, we are no longer dependent on the String type, as it was above. But then, at the output, we will get a Map with this type.

fun <T : Iterable<S>, S> findfrequency(list: T): MutableMap<S, Int> {
    val frequencyMap: MutableMap<S, Int> = HashMap()

    for (s in list) {
        var count = frequencyMap[s]
        if (count == null) count = 0
        frequencyMap[s] = count + 1
    }

    return frequencyMap
}