How to apply template to a string returned from a function


In Android text can be put on a resource file like

<string name="download_all">Download all $name</string>

and it can be retrieved by a call such as getString(download_all)

The problem is  the template expression doesn’t work in this situation ($name is not evaluated).


That resource string could be used anywhere. How would the compiler know what $name is referring to?

In this case, I think you should use:
MessageFormat.format(getString(R.string.download_all), name)
String.format(getString(R.string.download_all), name)


Unfortunately these calls do not work

  <string name="edit_sources_of_collection">Edit sources of '$collectionTitle'</string>

String.format(getString(R.string.edit_sources_of_collection)!!, collectionTitle)

generates error

Please specify constructor invocation; classifier ‘String’ does not have a class object

“”.format(getString(R.string.edit_sources_of_collection)!!, collectionTitle)


Edit sources of ‘$collectionTitle’

Ditto MessageFormat.formatgetString(R.string.edit_sources_of_collection)!!, collectionTitle)


I am sorry, I should have mentioned that you need to change your definition of the string too.

If you are going to use MessageFormat, you need to replace $variableName with {0}
If you are going to use String.format, you need to replace $variableName with %1$s

Both of them indicate that it should be replaced by the first argument of the format method.


For calling String.format, you have to preprend java.lang to let kotlin know that the method is on java.lang.String and not jet.String.

java.lang.String.format(formatString, arg1, arg2, …)


Ah ok. I am wondering whether there is a method that I can use to use the named templated expression instead of the positional one.

  <string name="edit_sources_of_collection">Edit sources of {0} </string>

is not very descriptive.


With MessageFormat, I think {0,,someName} works and is an easy way to attach a name for descriptive purposes.


Unfortunately the doc don't support this