kotlinpluralize

How can I combine two functions using default value?


I would like to combine these two function but I'm on trouble how to do it. Could anyone help me please?

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
    }
}

Solution

  • The real problem here is that you have a special requirement for this code and you did not mention this in your question. This is why all answers you get don't work for you. This additional requirement is that you need to use this function not only from Kotlin, but from Java and/or some reflection-based framework. And that changes a lot.

    Regular answer to your question is that you need to just use your second function, but declare its parameter as: plural: String? = null. This is enough to use it as you expect in Kotlin:

    "hour".pluralize(2) // hours
    "hour".pluralize(2, "foo") // foo
    

    But from the Java you will then only see a function receiving 3 parameters:

    PluralizeExtensionKt.pluralize("hour", 2, null); // hours
    PluralizeExtensionKt.pluralize("hour", 2, "foo"); // foo
    PluralizeExtensionKt.pluralize("hour", 2); // compile error
    

    To fix this problem, you need to additionally annotate this function with @JvmOverloads. This will generate two functions in the Java bytecode, so all above examples will work as you expect.

    The resulting function looks like this:

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

    Still, I suggest using an implementation provided in Михаил Нафталь answer. It fixes an additional bug in your code and is more concise.