Kotlin String.format


#1

Hi all

I am working on a Kotlin port of the Android Timber library for a quick introductory project. I have encountered an issue with (my use of?) the Kotlin standard lib. I am trying to use String.format with varargs.

 internal fun prepareLog(priority: Int, t: Throwable?, message: String, vararg args: Any?) {
       var outputMessage:String = message;
        if (!isLoggable(priority)) {
            return
        }

        if (outputMessage.length == 0) {
            if (t == null) {
                return  // Swallow message if it's null and there's no throwable.
            }
            outputMessage = getStackTraceString(t)
        } else {
            if (args.size > 0) {
                outputMessage.format(message, args)
            }
            if (t != null) {
                outputMessage += "\n" + getStackTraceString(t)
            }
        }

        log(priority, getTag(), outputMessage, t)
    }

However when I run this function I get the output Verbose message test [Ljava.lang.Object;@1878709 when calling the function with Verbose message test %s , "test"

Any thoughts on how I can make this work? It seems to work as designed if I call the method directly it seems to function as expected.


#2

You need to use the spread operator to pass a varargs argument to another method that takes a varargs parameter: outputMessage.format(message, *args)


#3

Thank you for the help yole that works as intended now.