建议的替换很难看,因为它需要等同于前面的代码:
- dependent on the default locale
- 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)