2013-03-06 25 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 "