2013-03-06 24 views
0

According to the documentation您可以引用<object.property>格式的对象的属性。我希望这可以让我检查一个字符串的长度,但它似乎不工作。我认为这是因为方法是String.length(),根据文档如果我做了类似<mystr.length>的文档,它将查找名为getLength()的方法和名为length的字段,但它从不查找名为length()的方法。我这个快速检查在斯卡拉REPL验证:在StringTemplate中获取字符串值的长度

scala> import org.stringtemplate.v4._; import scala.collection.JavaConverters._; 
import org.stringtemplate.v4._ 
import scala.collection.JavaConverters._ 

scala> new ST("<xs:{ x | <x>:<x.length> }>").add("xs", List("hello", "goodbye").asJava).render 
res0: String = "hello: goodbye: " 

scala> case class S(val s:String) { def getLength = s.length } 
defined class S 

scala> new ST("<xs:{ x | <x>:<x.length> }>").add("xs", List("hello", "goodbye").map(S).asJava).render 
res1: String = "S(hello):5 S(goodbye):7 " 

所以如果字符串有getLength()方法或length场会工作......

是否有更简单的方式来获得字符串的长度?也许是内置的StringTemplate函数,或者其他一些我不知道的方法?

回答

0

我发现在Cheatsheet's list of Functions答案:strlen

scala> new ST("<xs:{ x | <x>:<strlen(x)> }>").add("xs", List("hello", "goodbye").asJava).render 
res6: String = "hello:5 goodbye:7 "