2

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.

3
  • Because MessageFormat.format accept Object... and see sentences as one Object not an array of Object. In Kotlin not sure what to do... In Java it would be as simple as declaring sentences as an array. Commented Apr 27, 2018 at 12:37
  • 2
    Also, you need to assign the result of MessageFormat.format() to a variable and print that result. The code you posted can't produce the output you gave. Commented Apr 27, 2018 at 12:39
  • @JBNizet Thanks for your remaining. Commented Apr 27, 2018 at 12:50

2 Answers 2

5

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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, e.g. 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 *)

2 Comments

Thanks a lot. I do not know which answer should be accepted.You are both right.
@Lionel Briand answered a few seconds earlier, so it will be honest to accept his one :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.