Reputation: 3319
I have this scala template and want to use a case statement to render different html based on a matching enum value.
My template looks like this:
@(tagStatus: String)
try {
TagStatus.withName(tagStatus) match {
case TagStatus.deployed => {<span class="label label-success">@tagStatus</span>}
case TagStatus.deployedPartially => {<span class="label label-important">@tagStatus</span>}
case TagStatus.deployedWithProblems => {<span class="label label-important">@tagStatus</span>}
}
} catch {
{<span class="label label-important">??</span>}
}
The enum looks something like this:
object TagStatus extends Enumeration{
val deployed = Value("deployed")
val deployedWithProblems = Value("deployed_with_problems")
val deployedPartially = Value("deployed_partially")
}
When i run this i get:
Compilation error
')' expected but 'case' found.
In C:\...\statusTag.scala.html at line 8.
5 case TagStatus.deployed => {<span class="label label-success">@tagStatus</span>}
6 case TagStatus.deployedPartially => {<span class="label label-important">@tagStatus</span>}
7 case TagStatus.deployedWithProblems => {<span class="label label-important">@tagStatus</span>}
8 }
9 } catch {
10 {<span class="label label-important">??</span>}
11 }
I have not idea what is meant by this error message.
What am i missing in order to get this simple code snippet to compile?
Thanks!
Upvotes: 2
Views: 3247
Reputation: 4391
toString is not compatible with match so convert the String to the enum using withName
You can do it like this - I am not quite sure of the Play syntax:
TagsStatus.withName(tagStatus) match {
case TagStatus.deployed => {<span class="label label-success">@tagStatus</span>}
case TagStatus.deployedPartially => {<span class="label label-important">@tagStatus</span>}
case TagStatus.deployedWithProblems => {<span class="label label-important">@tagStatus</span>}
case _ => {<span class="label label-important">??</span>}
}
BTW there is a common related issue concerning Scala pattern matching with lower case variable names
Upvotes: 4
Reputation: 562
You don't have to use try here, just the wild card in you match (see: http://www.playframework.com/documentation/2.1.x/ScalaTemplateUseCases).
@(tagStatus: String)
@tagStatus match {
case TagStatus.deployed.toString => {<span class="label label-success">@tagStatus</span>}
case TagStatus.deployedPartially.toString => {<span class="label label-important">@tagStatus</span>}
case TagStatus.deployedWithProblems.toString => {<span class="label label-important">@tagStatus</span>}
case _ => {<span class="label label-important">??</span>}
}
Upvotes: 3