当字符串来自Kotlin中的字符串资源文件时,为什么还没有替换?

时间:2018-06-30 08:44:12

标签: android kotlin

使用代码A时,得到原始字符串,为什么?

代码B可以同时替换字符串var canvas = new fabric.Canvas('c5'); function some1(x1, y2) { var c = new fabric.Triangle({ left: posX2, top: posY2, width: 15, height: 25, strokeWidth: 3, fill: '#666', stroke: '#666' }); canvas.add(c); } var posX2, posY2; canvas.on('mouse:down', function(e) { var pointer = canvas.getPointer(e.e); posX2 = pointer.x; posY2 = pointer.y; if (e.target) {} else { some1(posY2, posY2); } }); function saveJsonF() { var jsonToPHP = JSON.stringify(canvas.toObject()); console.log(jsonToPHP); } document.getElementById("saveJsonID").onclick = saveJsonF;<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.min.js"></script> <input type="button" class="Btn1" id="saveJsonID" value="Save" /></br><br> <canvas id="c5" width="1060" height="550" style="border: 1px solid black"></canvas>,结果正常。

图片

enter image description here

代码A

${myObject.status}

代码B

${myObject.name}

1 个答案:

答案 0 :(得分:2)

Kotlin编译器在编译时将字符串文字转换为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");

如果您通过资源加载,则没有转换,它会按原样使用。但是,您可以使用格式表string resource

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

然后在读取字符串时注入参数(如果实时提供过多的参数或错误的类型,Android Studio甚至会纠正您):

val s=mContext.getString(R.string.DetailsOfWiFiDef, myObject.status, myObject.name)