Skip to content

Instantly share code, notes, and snippets.

@lnds
Created May 22, 2017 19:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lnds/2dcef9cbfedce1f7ae1aa2d59760491b to your computer and use it in GitHub Desktop.
Save lnds/2dcef9cbfedce1f7ae1aa2d59760491b to your computer and use it in GitHub Desktop.
A java interop bug in Kotlin
/*
** In java remove() is overloaded
** for Class ArrayList<E>
** we have:
**
** public E remove(int index)
** Removes the element at the specified position in this list.
**
** public boolean remove(Object o)
** Removes the first occurrence of the specified element from this list
**
** Kotlin declares ArrayList<E> with a typealias:
**
** @SinceKotlin("1.1") public typealias ArrayList<E> = java.util.ArrayList<E>
**
** In Java we have Integer and int.
** In Kotlin we only have Int
** And see what happens when we try to use remove() with an Int
*/
fun main(args:Array<String>) {
var list = ArrayList<Int>()
list.add(0)
list.add(0)
list.remove(list.size-1) // try to remove last element on list, but Kotlin call remove(Object o), no remove(int index)
list.forEachIndexed { i, v ->
println("list(" + i +") = "+v)
}
println("")
// you must call removeAt
list.removeAt(list.size-1)
list.forEachIndexed { i, v ->
println("list(" + i +") = "+v)
}
}
@MarioAriasC
Copy link

Not a bug. Kotlin collections under the hood are Java Collections but Kotlin offers a different API

@lnds
Copy link
Author

lnds commented Jun 10, 2017

The bug is that Int in Kotlin hides Integer, but list.remove() is overloaded to receive int and Integer, and in Kotlin you can´t pass an int. It´s not a Kotlin bug, is a sutil bug induced by java decision over "native types" and that boxing unboxing thing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment