将var-args传递给kotlin中的MessageFormat.format

我想解析errorCode像

4011=Error thrown expected: {0} found: {1}. 

在kotlin中使用Message.format

 loggingService.logTheMsg("4011", arrayOf("${expectedVal}", "${actualVal}")) 

在logTheMsg我使用这个代码:

 var errorMessage = props.getProperty(errorCode) errorMessage = MessageFormat.format(errorMessage as String, args) println("${errorMessage}.") 

但获取输出为:

 Error thrown expected:[Ljava.lang.String;@38f3b4ba found: {1}. 

这可能有助于回答,同样的事情在java中是这样实现的:

 parse(value, new String[]{"firstName","lastName"}); 

在解析:

 parse(String value, String[]args) { value = MessageFormat.format((String) value, args); System.out.println(value); } 

打印:我的名字是名字姓氏

为了消除模糊性,Kotlin需要在数组上传递“spread operator”(*)作为参数,即

 loggingService.logTheMsg("4011", *arrayOf("${expectedVal}", "${actualVal}")) 

此外, "${expectedVal}"应该用expectedVal替换:

 loggingService.logTheMsg("4011", *arrayOf(expectedVal, actualVal)) 

而且,当然,你可以使用可变参数作为打算使用的参数:

 loggingService.logTheMsg("4011", expectedVal, actualVal)