`joinToString` function parameter for last separator value


#1

I have a feature request for the joinToString() function.

What I’m regularly encountering is using this function for a message, and I would like to put something else before the last item in the list.

Example

Let’s say we wan’t to validate on a list of allowed values

fun validateAllowedValue(value: String) {
    val allowedValues = listOf("foo", "bar", "baz")
    if (value !in allowedValues)
        throw IllegalArgumentException("$\"value\" is invalid. Allowed values are ${allowedValues.joinToString()}")
}

fun main(args: Array<String>) {
    validateAllowedValue("something invalid")
}

Which results in

    // Results in 
   Exception in thread "main" java.lang.IllegalArgumentException: "something invalid" is invalid. Allowed values are foo, bar, baz
	at chapter_10_functors_applicatives_monads.DeletemeKt.validateAllowedValue(deleteme.kt:6)
	at chapter_10_functors_applicatives_monads.DeletemeKt.main(deleteme.kt:10)

Process finished with exit code 1

A nicer message would be:

Exception in thread "main" java.lang.IllegalArgumentException: "something invalid" is invalid. Allowed values are foo, bar or baz

Request

My request is to add a parameter for the last separator.

allowedValues.joinToString(last="or")

// or

allowedValues.joinToString(lastSeparator="or")

#2

Thanks for the suggestion! Please create a feature request at http://kotl.in/issue, this is a proper place for such things.


#3

Thanks,

I have copied the issue https://youtrack.jetbrains.com/issue/KT-25795


#4

You could use KBox, a very small utility library which provides this functionality:


#5

Good one, thanks @robstoll


#6

IMHO it is very unusual task and it do not excuse additional logic for frequently used method