Reputation: 4230
MutableList
is an interface, but I cannot find a class in kotlin
package that implements it explicitly. Is there any? Furthermore, I would have expected to be a package-scope defined mutableListOf(varargs) symetrically to listOf(varargs). Up until now, I have to use java Collections.
Upvotes: 20
Views: 5513
Reputation: 8335
No, as far as Collections are concerned you can not avoid java API's, Because every kotlin collection uses corresponding java collection in one way or another.
Kotlin collection interfaces are just mock interfaces, they don't really exist at runtime. So even if you had a class implementing some kotlin collection interface(ex. MutableList
) at runtime it would use corresponding java interface.
for example let's write two kotlin classes implementing kotlin's List
and MutableList
interfaces respectively
abstract class KotlinList : List<Int>
abstract class KotlinMutableList : MutableList<Int>
when you decompile these classes their signature's change as following (heads up, byte code ahead)
public abstract class com/example/kotlin/KotlinList implements java/util/List kotlin/jvm/internal/markers/KMappedMarker
public abstract class com/example/kotlin/KotlinMutableList implements java/util/List kotlin/jvm/internal/markers/KMutableList
Now both the classes implement java.util.List
interface and they also implement kotlin.jvm.internal.markers.KMappedMarker
and kotlin.jvm.internal.markers.KMutableList
interfaces respectively, so as you can see kotlin interfaces has disappeared and we are left with same old java List
and your methods calls will now be addresses as java.util.List.someMethod and not with some kotlin interface. KMutableList
and KMappedMarker
as their name suggests are marker interfaces used by the the compiler.
In case of KotlinList
class if you look inside you will see all mutater methods of java.util.List
are generated for you and look similar to the one below
public boolean add(int var1) {
throw new UnsupportedOperationException("Operation is not supported for read-only collection");
}
So as you can see there is no way of avoiding java API's, because they are the foundation of kotlin's collections.
Upvotes: 0