Search code examples
guavakotlin

Kotlin type inference fails for guava TreeMultimap


I have:

data class Edge(val spec: String, val weight: Int)
private val graph: SortedSetMultimap<String, Edge> = TreeMultimap.create()

The call to create() is an error:

MapCrawler.kt: (63, 71): Type inference failed. Expected type mismatch: inferred type is TreeMultimap<(???..???), (???..???)>! but SortedSetMultimap was expected

If I change it to be a

SortedSetMultimap<String, String> 

it works fine (no issues with the type inference). In other words, this line compiles just fine:

private val graph: SortedSetMultimap<String, String> = TreeMultimap.create()

What is it about the Edge class that messes up the type inference, and how do I fix it?


Solution

  • You need to pass two comparator implementation to create function. Have a look at following snippet:

    private val graph:SortedSetMultimap<String, Food> = TreeMultimap.create(Comparator<String> { str1, str2 -> 0
            // compare string here
        }, Comparator<Food> { edge1, edge2 -> 0
            // compare Edge object here
        })
    

    I have tested this it works. You can remove data type (:SortedSetMultimap<String, Food>) as assignment statement can infer which type of value is being returned.

    Hope this helps.