Home > OS >  Kotlin does not allow charAt
Kotlin does not allow charAt

Time:11-03

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)
    }
}

CodePudding user response:

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...

CodePudding user response:

It's possible to simply use array indexing.

@Test
    fun `myChar is M`() {
        val buffer: CharBuffer = CharBuffer.wrap("MyString")
        val myChar = buffer[0]
        assert(myChar == 'M') { "myChar is not M" }
    }
}

CharBuffer implements CharSequence and you can find out more about it in the kotlin docs.

  • Related