Home > Back-end >  Any difference between String.getOrElse() and String.elementAtOrElse()?
Any difference between String.getOrElse() and String.elementAtOrElse()?

Time:12-03

As the title states:

Is there any difference between String.getOrElse() and String.elementAtOrElse()? From a functional point of view they seem completely identical, maybe some performance difference?

Same question accounts to String.getOrNull() and String.elementAtOrNull().

CodePudding user response:

Looking at the implementation in https://github.com/JetBrains/kotlin/blame/master/libraries/stdlib/common/src/generated/_Strings.kt they look identical.

/**
 * Returns a character at the given [index] or the result of calling the [defaultValue] function if the [index] is out of bounds of this char sequence.
 * 
 * @sample samples.collections.Collections.Elements.elementAtOrElse
 */
@kotlin.internal.InlineOnly
public inline fun CharSequence.elementAtOrElse(index: Int, defaultValue: (Int) -> Char): Char {
    return if (index >= 0 && index <= lastIndex) get(index) else defaultValue(index)
}
/**
 * Returns a character at the given [index] or the result of calling the [defaultValue] function if the [index] is out of bounds of this char sequence.
 */
@kotlin.internal.InlineOnly
public inline fun CharSequence.getOrElse(index: Int, defaultValue: (Int) -> Char): Char {
    return if (index >= 0 && index <= lastIndex) get(index) else defaultValue(index)
}

I hope somebody else can provide details about the history of this.

CodePudding user response:

To explain the why:

From the issue that added these over at https://youtrack.jetbrains.com/issue/KT-6952 it appears that elementAtOrElse() was added first and named such for compatibility with Iterables, while getOrElse() was added later for compatibility with Lists.

CodePudding user response:

The very links you included in your question allow you to see the source code of each implementation which tells you that, no, there is no difference.

In fact elementAtOrNull literally just calls getOrNull.

  • Related