How can I use Java's String (String) method directly from Kotlin source?

While doing some profiling, it seems like my bottleneck is the Kotlin extension function kotlin.CharSequence.split()

.

My code just does something like this:

val delimiter = '\t'
val line = "example\tline"
val parts = line.split(delimiter)

      

As you might have noticed, parts

this is List<String>

.

I wanted to directly compare Java split

which returns String[]

and might be more efficient.

How can I call Java String::split(String)

directly from Kotlin source?

+3


source to share


2 answers


You can apply kotlin.String

to java.lang.String

and then use java.lang.String#split

as it kotlin.String

will be mapped before java.lang.String

, but you will get warnings. eg:

//                               v--- PLATFORM_CLASS_MAPPED_TO_KOTLIN warnings
val parts: Array<String> = (line as java.lang.String).split("\t")

      

You can use instead java.util.regex.Pattern#split

, since according to @Renato it will be slower than java.lang.String#split

in some situations. eg:



val parts: Array<String> = Pattern.compile("\t").split(line, 0)

      

But be careful, the behavior kotlin.String#split

is different from java.lang.String#split

, for example:

val line: String = "example\tline\t"

//   v--- ["example", "line"]
val parts1: Array<String> = Pattern.compile("\t").split(line, 0)

//   v--- ["example", "line", ""]
val parts2 = line.split("\t".toRegex())

      

+4


source


You can do it:

(line as java.lang.String).split(delimiter)

      



But it is not recommended not to use kotlin.String

, as the compiler might tell you.

+2


source







All Articles