Created
May 22, 2017 19:01
-
-
Save lnds/2dcef9cbfedce1f7ae1aa2d59760491b to your computer and use it in GitHub Desktop.
A java interop bug in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
** 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) | |
} | |
} |
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
Not a bug. Kotlin collections under the hood are Java Collections but Kotlin offers a different API