How to create LinkedHashMap with accessOrder in Kotlin

91 Views Asked by At

I'm trying to create new instance of LinkedHashMap like this:

class LRUCache<K, V>(
    private val size: Int
) {
    private val cache = LinkedHashMap<K, V>(size, loadFactor = 0.75F, accessOrder = true)
}

but it wont compile, reporting error:

Kotlin: None of the following functions can be called with the arguments supplied: 
public constructor LinkedHashMap<K : Any!, V : Any!>(p0: (MutableMap<out TypeVariable(K)!, out TypeVariable(V)!>..Map<out TypeVariable(K)!, TypeVariable(V)!>?)) defined in java.util.LinkedHashMap
public constructor LinkedHashMap<K : Any!, V : Any!>(p0: Int) defined in java.util.LinkedHashMap

Looks like kotlin "doesn't see" constructor with three arguments, but it exists in java.

1

There are 1 best solutions below

0
Sweeper On

The problem here is that you are calling it with named parameters. This is not supported for Java APIs.

When calling Java functions on the JVM, you can't use the named argument syntax because Java bytecode does not always preserve the names of function parameters.

So indeed Kotlin doesn't find any of the Java constructors. It only finds these common ones that are declared in Kotlin.

You need to remove the parameter names:

LinkedHashMap<K, V>(size, 0.75f, true)