0

When I use Code A, I get the original string ,why?

Code B can replace string both ${myObject.status} and ${myObject.name}, the result is OK.

Image

enter image description here

Code A

<string name="DetailsOfWiFiDef">The WiFi status is ${myObject.status},
        the name of WiFi is ${myObject.name}\n\n
</string>

val myObject=getIt()
val s=mContext.getString(R.string.DetailsOfWiFiDef)
val sb = StringBuilder()
sb.append(s)  //The string keep original

Code B

val myObject=getIt()
val k="The WiFi status is ${myObject.status},the name of WiFi is ${myObject.name} \n"
val sb = StringBuilder()
sb.append(k)  //It has been replaced         

1 Answer 1

2

Kotlin compiler converts string literals into StringBuilder chain at compile time:

// code in Kotlin
val k = "The WiFi status is ${myObject.status},the name of WiFi is ${myObject.name} \n"

// is converted into equivalent of code in Java
String k = new StringBuilder("The WiFi status is ").append(myObject.getStatus()).append(",the name of WiFi is ").append(myObject.getName()).append(" \n");

If you load through resources there's no conversion, it's used as is. However you can use formattable string resource:

<string name="DetailsOfWiFiDef">The WiFi status is %1$s,
        the name of WiFi is %2$s\n\n
</string>

Then inject arguments when reading string (Android Studio even corrects You if you proide too many arguments or wrong type in real time):

val s=mContext.getString(R.string.DetailsOfWiFiDef, myObject.status, myObject.name)
Sign up to request clarification or add additional context in comments.

Comments

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.