Any difference between String.getOrElse() and String.elementAtOrElse()?

Viewed 939
3 Answers

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.

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.

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