Kotlin不赞成String类上的capitalize函数,而且他们建议的替换太长了.这是一个例子,他们在不推荐它时做出了正确的决定,但在用户体验上做出了错误的决定.

例如,此代码:

val x = listOf("foo", "bar", "baz").map { it.capitalize() }

被IDE"清理"成:

val x = listOf("foo", "bar", "baz").map { it.replaceFirstChar {
                    if (it.isLowerCase()) it.titlecase(
                        Locale.getDefault()
                    ) else it.toString()
                } }

这太难看了.我们能做些什么?

推荐答案

建议的替换很难看,因为它需要等同于前面的代码:

  1. dependent on the default locale
  2. NOT converting an uppercase first char into titlecase (e.g. capitalize does NOT transform a leading 'DŽ' into 'Dž' - both are single characters here, try to select them)

如果您不太关心此行为,您可以使用一个更简单的表达式,使用不变的区域设置,并无条件地命名第一个字符,即使是大写:

val x = listOf("foo", "bar", "baz").map { it.replaceFirstChar(Char::titlecase) }

这意味着如果第一个字符是大写的,比如'DŽ',那么它无论如何都会被转换成标题库变体'Dž',而原始代码不会接触到它.这实际上可能是可取的.

One of the reasons capitalize() has been deprecated is because the behaviour of the method was unclear. For instance, behaviour #2 is pretty weird, and the behaviour of not capitalizing words in a sentence might be unexpected (C# would titlecase every space-separated word).

如果您想故意保留当前的确切行为,但使其更便于使用,您可以始终使用适合自己的名称来滚动自己的扩展函数("大写(d)"可能无法向不知情的读者提供足够的信息):

fun String.titlecaseFirstCharIfItIsLowercase() = replaceFirstChar { 
    if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() 
}

或者对于标题为大写字符的固定区域设置版本:

fun String.titlecaseFirstChar() = replaceFirstChar(Char::titlecase)

Kotlin相关问答推荐

等待下一个值时暂停Kotlin Coroutine

为什么";";.equals(1)在柯特林语中是有效的,但";";=1是无效的?

Kotlin接口方法默认值&;可传递依赖项

同时也是一个字符串的 Kotlin 枚举

使用 Jetpack Compose 使用参数导航

Kotlin 条件格式字符串

is return inside function definition 也是 kotlin 中的表达式

如何在 Kotlin for Android 上使用setTextColor(hexaValue),

Kotlin 中多个 init 块的用例?

为什么 Kotlin 需要函数引用语法?

使用最新的 com.jakewharton.rxbinding3:rxbinding:3.0.0-alpha2 库时未找到 RxTextView 和其他小部件

Gradle 同步失败:不支持的方法:KotlinPlatformContainer.supports()

Kotlinwhen表达式在使用主题时是否支持复合布尔表达式?

使用 Paging 3 时保存并保留 LazyColumn 滚动位置

更新到版本4.10.1/4.10.2后 Gradle 同步失败

如何在Kotlin中创建无限长的序列

在 Kotlin 中创建 Spinner 时,如何在 Fragment 中的旋转屏幕上修复指定为非空的参数为空?

Gradle:无法连接到 Windows 上的 Kotlin 守护程序

如何将vararg作为数组传递给Kotlin中的函数?

旋转 kotlin 数组