3

使用 Kotlin 1.5 时,Android Studio 会发出警告,该版本String.capitalize已弃用。

建议的替换是:

myString.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() })

为什么检查是isLowerCase必要的?

为什么我不能这样做:

myString.replaceFirstChar { it.titlecase(Locale.getDefault()) })
4

1 回答 1

5

门票报价:

此外,用户可能对 的行为有不同fun String.capitalize(): String的期望,并且期望并不总是与我们实施的一致(参见KEEP讨论)。仅当接收者的第一个字符String是小写字母时,该函数才将其首字母大写。例如, is 的结果"DŽ".capitalize()"DŽ""dž".capitalize()is "Dž"。考虑到不同的期望,我们想引入 replaceFirstChar 函数让用户准确地编写他们想要的代码。

替换是冗长的,但尽可能保持行为接近。如果需要更简单的行为,则可以进一步简化生成的代码,例如String.replaceFirstChar { it.uppercaseChar() }.


以下是基于我的想法的原始答案。另请查看评论,因为有一个很好的说明

我想这是因为他们想复制原始行为。目前capitalize 实施为:

public fun String.capitalize(locale: Locale): String {
    if (isNotEmpty()) {
        val firstChar = this[0]
        if (firstChar.isLowerCase()) {
            return buildString {
                val titleChar = firstChar.titlecaseChar()
                if (titleChar != firstChar.uppercaseChar()) {
                    append(titleChar)
                } else {
                    append(this@capitalize.substring(0, 1).uppercase(locale))
                }
                append(this@capitalize.substring(1))
            }
        }
    }
    return this
}

此外,根据注释:

一个字符的标题大小写通常与其大写相同,但有几个例外。

有一些极端情况:

fun check(x: String) {
    println(x.capitalize())
    println(x.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() })
    println(x.replaceFirstChar { it.titlecase() })
}

fun main() {
    check("dz")
    check("DZ")
}

输出(操场):

Dz
Dz
Dz
DZ
DZ
Dz
于 2021-05-16T07:13:17.830 回答