简体   繁体   中英

Java MessageFormat cannot format

Here is a string template read from file.

Dialogue: {0}
Dialogue: {1}

After I read it from file, I want to format this string using given array.

var sentences = arrayOf("hello", "world")
var template = File("file_path").readText()

template = MessageFormat.format(template, sentences)

print(template)

But I get output.

Dialogue: [Ljava.lang.String;@27c170f0
Dialogue: {1}

EDIT

If I put array elements one by one, I will get right output.

The sentence variable is an array and not multiple argument. You have to to put a * ( spread operator ) before to transform it into vararg.

MessageFormat.format(template, *sentences)

You can use spread operator * :

MessageFormat.format(template, *sentences)

It will transform an array into vararg to match format method signature:

format(String pattern, Object... arguments)

From the docs:

When we call a vararg-function, we can pass arguments one-by-one, eg asList(1, 2, 3), or, if we already have an array and want to pass its contents to the function, we use the spread operator (prefix the array with *)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM