Home > Software design >  How to print a part of a string in kotlin and why am I getting this error?
How to print a part of a string in kotlin and why am I getting this error?

Time:02-26

val me = "Hello I am learning Kotlin"
fun main(){
    println(me[1,10])
}

I am getting "Too many arguments for public open fun get(index: Int): Char defined in kotlin.String" error at line 3 why? And How can I print a part of a string in kotlin. According to https://kotlinlang.org/docs/operator-overloading.html#indexed-access-operator line 3 should work but its giving me too many arguments ERROR.

CodePudding user response:

The indexed operator function for a String only takes one argument. The documentation that you linked to is showing you how indexed operator overloads are interpreted if you define them that way. The one for String is only defined for one argument.

However, you can define your own extension function for String like this, and then your syntax would work:

operator fun String.get(firstIndex: Int, vararg otherIndices: Int) = buildString {
    append(this@get[firstIndex])
    for (i in otherIndices) append(this@get[i])
}

  • Related