Why hasn't the string been replaced when it is from string resource file in Kotlin?
Why hasn't the string been replaced when it is from string resource file in Kotlin?
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.
${myObject.status}
${myObject.name}
Image

Code A
<string name="DetailsOfWiFiDef">The WiFi status is ${myObject.status},
the name of WiFi is ${myObject.name}nn
</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
Kotlin compiler converts string literals into StringBuilder chain at compile time:
StringBuilder
// 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$snn
</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)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.