21

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().

Markus Weninger
  • 11,931
  • 7
  • 64
  • 137
  • 7
    Great question! It would be interesting to hear the history behind this. My bet is on some arcane old compatibility layers with JVM or JS. – Hubert Grzeskowiak Dec 02 '21 at 06:15

3 Answers3

10

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.

Markus Weninger
  • 11,931
  • 7
  • 64
  • 137
Nzall
  • 3,439
  • 5
  • 29
  • 59
8

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.

Hubert Grzeskowiak
  • 15,137
  • 5
  • 57
  • 74
4

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.

dominicoder
  • 9,338
  • 1
  • 26
  • 32