0

I have a List of Objects and want to iterate every Element in this List to get their Id Strings. Those Strings must be saved into another List. I always get this Compiler Error:

    [error] FilePath:line:64: illegal start of simple expression
    [error]                 @var formNameList : Array[String] = new Array[String](formList.size())
    [error]                  ^
    [error] File Path:69: ')' expected but '}' found.
    [error]     }
    [error]       ^
    [error] two errors found
    [error] (compile:compile) Compilation failed
    [error] Total time: 3 s, completed 05.12.2013 14:03:37

So please guys help, before I drive insane.

My Code:

@var formNameList : Array[String] = new Array[String](formList.size())
     @for(i <- 0 until formList.size()) {
            @formNameList.add(formList.get(i).getFormId())
     }
     @views.html.formmanager.showresults(formNameList, formManager)

Im a Newbie in Scala and this is a very simple Task in Java but Scala is such a tough language. Its also very hard to read: What does this .:::, ::: or this <++= mean?

1 Answer 1

3

Short answer:

@views.html.formmanager.showresults(formList.map(_.getFormId).toArray, formManager)

Long answer:

Scala templates are templates - they should be used to generate some presentation of data and not be used as placeholders for a general code. I would strongly advice against doing any mutable or complex computations inside of templates. If you have complex code you should either pass it as a parameter or create a helper object like this:

# in helper.scala:
object Helper {
  def toArrayOfIds(formList:List[Form]) = formList.map(_.getFormId).toArray
}
# in view.scala.html:
@Helper.toArrayOfIds(formList)

Another thing - prefer List to an Array. Usually I never use Array in my scala programms. Also notice the use of higher order function map instead of creating array an manually populating it. This is highly recommended. Just see how short the first example is.

.:::, ::: <++= could mean different things in different contexts. Usually first two operators mean the same thing which is concatenation of two lists. You can read about this in the "Programming in Scala" by Martin Odersky, first edition is available for free.

And if you need to introduce new variable in the template you can do it like this:

@defining(user.firstName + " " + user.lastName) { fullName =>
  <div>Hello @fullName</div>
}

see play documentation

Sign up to request clarification or add additional context in comments.

1 Comment

First of all thanks for this nice answer. I need both arrays in my template so I thought just to create them there, but you are right. I pass it now as a parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.