You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用默认值合并两个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 pluralize adds 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? = null as 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 custom plural was 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:

  1. Using the default 's' suffix (matches your first function):
    val apple = "apple"
    println(apple.pluralize(1)) // Output: apple
    println(apple.pluralize(5)) // Output: apples
    
  2. 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
    
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 11:32:31