Reputation: 39
I want this code refactoring. if size == 5... i don't want add code. just use for loop or stream or other solution as size args set.
private fun formatTest(args: List<String>): String {
var size = args?.size
return when {
size == 1 -> java.lang.String.format(code.message, args[0])
size == 2 -> java.lang.String.format(code.message, args[0], args[1])
size == 3 -> java.lang.String.format(code.message, args[0], args[1], args[2])
size == 4 -> java.lang.String.format(code.message, args[0], args[1], args[2], args[3])
else -> java.lang.String.format(code.message)
}
}
Upvotes: 2
Views: 586
Reputation: 273380
First, convert the list to an array, then use the *
operator to "spread" the array into the varargs.
private fun formatTest(args: List<String>) =
if (args.size < 5) {
String.format(code.message, *args.toTypedArray())
} else {
code.message
}
Upvotes: 4