Kotlin does not allow charAt

Issue

Why java compiles when kotlin not? And how to invoke charAt in kotlin?

Java:

import java.nio.CharBuffer;

public class Test {
    public static void test() {
        CharBuffer buffer  CharBuffer.wrap("asd");
        buffer.charAt(0);
    }
}

Kotlin:

import java.nio.CharBuffer

class TestKotlin {
    fun test() {
        val buffer  CharBuffer.wrap("asd")
        buffer.charAt(0)
    }
}

Solution

I am theorizing from looking at this old issue that the Kotlin developers at one time accidentally treated CharBuffer.charAt() and CharBuffer.get() as equivalent and hid the charAt() method in Kotlin and mapped it to get(). They might have done this in an effort to promote the use of array-access syntax (brackets) and avoid supposed redundancy.

And perhaps later when the above issue was fixed, they missed unhiding the method.

buffer.charAt(i) would be buffer[buffer.position() + i] in Kotlin. You could write an extension function so you can continue to use it:

fun CharBuffer.charAt(index: Int)  this[position() + index]

The error message if you choose an out-of-bounds index will be slightly less informative than the one in the original method.

Maybe someone should open an issue on YouTrack for this…

Answered By – Tenfour04

Leave a Comment