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()
.
We can use this in a scenario where we have to give some default value for the empty input. Also, it is very easy to use, readable and under stable by the developer, and also it is available for both Some and none class of Option in scala. This is a guide to Scala getOrElse.
String is an alias for System.String class and instead of writing System.String one can use String which is a shorthand for System.String class and is defined in the .NET base class library.
String class is immutable. StringBuffer class is mutable. String is slow and consumes more memory when you concat too many strings because every time it creates new instance. StringBuffer is fast and consumes less memory when you cancat strings. String class overrides the equals () method of Object class.
Clearly, orElse () takes any parameter of a type T, whereas orElseGet () accepts a functional interface of type Supplier that returns an object of type T. Based on their Javadocs: 3. Differences
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 Iterable
s, while getOrElse()
was added later for compatibility with List
s.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With