如何使用默认值合并两个Kotlin pluralize扩展函数?
Merging Your Kotlin Pluralize Extension Functions
Hey there! Great question—combining these two functions is totally doable thanks to Kotlin's handy default parameter support. Let's work through this together.
First, let's recap what your original functions handle:
- The first
pluralizeadds an 's' to the string when the count isn't 1, otherwise returns the original value. - The second lets you specify a custom plural form, falling back to the 's' suffix if the custom plural is null.
Instead of keeping two separate functions, we can merge them into one function with a default parameter for the plural value. Here's the clean merged version:
fun String?.pluralize(count: Int, plural: String? = null): String? { return if (count != 1) { plural ?: this + 's' } else { this } }
How this works:
- We set
plural: String? = nullas a default parameter—this means if you don't pass a plural value when calling the function, it defaults to null, replicating the behavior of your first original function. - When
count != 1, we first check if a custompluralwas provided. If yes, we use that. If not (or if it's null), we fall back to appending 's' to the original string—exactly like your first function. - When
count == 1, we just return the original string, matching the behavior of both original functions.
Example usage to confirm it covers all cases:
- Using the default 's' suffix (matches your first function):
val apple = "apple" println(apple.pluralize(1)) // Output: apple println(apple.pluralize(5)) // Output: apples - Using a custom plural form (matches your second function):
val child = "child" println(child.pluralize(2, "children")) // Output: children // Even if you pass null as the custom plural, it falls back to 's' println(child.pluralize(3, null)) // Output: childs - Handling null strings (preserves your original behavior):
val nullString: String? = null println(nullString.pluralize(2)) // Output: nulls println(nullString.pluralize(1)) // Output: null
This merged function keeps all the functionality of your two original functions while being more concise and maintainable—win-win!
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

