Search code examples
kotlinextension-function

Calling Kotlin extension function from Java from kotlin.text package


I'm trying to use toRegex() extension function from the kotlin.text package from my Java code. Here is the code of that file:

/*
 * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
 * that can be found in the license/LICENSE.txt file.
 */

@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("StringsKt")

package kotlin.text

/**
 * Converts the string into a regular expression [Regex] with the default options.
 */
@kotlin.internal.InlineOnly
public inline fun String.toRegex(): Regex = Regex(this)

/**
 * Converts the string into a regular expression [Regex] with the specified single [option].
 */
@kotlin.internal.InlineOnly
public inline fun String.toRegex(option: RegexOption): Regex = Regex(this, option)

/**
 * Converts the string into a regular expression [Regex] with the specified set of [options].
 */
@kotlin.internal.InlineOnly
public inline fun String.toRegex(options: Set<RegexOption>): Regex = Regex(this, options)

Unfortunately I had no success calling the function from Java code. I think I'm missing something. Here is my attempt:

import kotlin.text.StringsKt;
...

StringsKt.toRegex("some_string"); // Doesn't compile.

Doesn't compile.


Solution

  • This is caused by the @InlineOnly annotation on that function.

    InlineOnly means that the Java method corresponding to this Kotlin function is marked private so that Java code can not access it (which is the only way to call an inline function without actually inlining it).


    Also, this is a potential duplicate of this question, although it doesn't directly ask about @InlineOnly.