String.getOrElse() 和 String.elementAtOrElse() 之间有什么区别?

Mar*_*ger 21 kotlin

正如标题所说:

String.getOrElse()和之间有什么区别吗String.elementAtOrElse()?从功能的角度来看,它们看起来完全相同,也许有一些性能差异?

同样的问题涉及String.getOrNull()String.elementAtOrNull()

Nza*_*all 11

解释一下原因:

从在https://youtrack.jetbrains.com/issue/KT-6952添加这些内容的问题来看,elementAtOrElse()首先添加并命名是为了与Iterables 兼容,而getOrElse()后来添加是为了与Lists 兼容。


Hub*_*iak 8

查看https://github.com/JetBrains/kotlin/blame/master/libraries/stdlib/common/src/ generated/_Strings.kt 中的实现,它们看起来相同。

/**
 * 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)
}
Run Code Online (Sandbox Code Playgroud)
/**
 * 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)
}
Run Code Online (Sandbox Code Playgroud)

我希望其他人可以提供有关此历史的详细信息。