Frage

According to the documentation you can reference properties of objects in the <object.property> format. I was hoping this would let me check the length of a String, but it doesn't seem to work. I think this is because the method is String.length(), and according to the documentation if I do something like <mystr.length> it will look for a method called getLength() and a field named length, but it never looks for a method called length(). I verified with this quick check in the Scala REPL:

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 "

So if Strings had a getLength() method or a length field it would work...

Is there an easier way to get the String length? Maybe a built-in StringTemplate function, or some other method that I don't know about?

War es hilfreich?

Lösung

I found the answer in the 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 "
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top