首页 > 解决方案 > 如何使用默认值组合两个函数?

问题描述

我想将这两个功能结合起来,但我很难做到。有人可以帮我吗?

fun String?.pluralize(count: Int): String? {
    return if (count != 1) {
        this + 's'
    } else {
        this
    }
}

fun String?.pluralize(count: Int, plural: String?): String? {
    return if (count != 1) {
        plural ?: this + 's'
    } else {
        this
    }
}

标签: kotlinpluralize

解决方案


获得所需结果并处理null输入情况的正确方法String应该如下:

fun String?.pluralize(count: Int, plural: String? = null): String? = when {
    count == 1 || this == null -> this
    else -> plural ?: "${this}s"
}

推荐阅读