How can I cast from a String to a long in a Scala play 2.0 template?
I want to do the following where I have the action: Application.profile(Long user_id)
:
<a href='@routes.Application.profile((Long) session.get("user_id"))'>@session.get("username")</a>
Starting Scala 2.13
you might prefer String::toLongOption
in order to safely handle String
s which can't be cast to Long
:
"1234".toLongOption.getOrElse(-1L) // 1234L
"lOZ1".toLongOption.getOrElse(-1L) // -1L
"1234".toLongOption // Some(1234L)
"lOZ1".toLongOption // None
In your case:
session.get("user_id").toLongOption.getOrElse(-1L)
With earlier versions, you can alternatively use a mix of String::toLong
and Try
:
import scala.util.Try
Try("1234".toLong).getOrElse(-1L) // 1234L
Try("lOZ1".toLong).getOrElse(-1L) // -1L
Casting doesn't work like that in Scala.
You want:
session.get("user_id").toLong
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With