Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting String to Long in Scala in template play 2.0 template

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>
like image 343
wfbarksdale Avatar asked May 02 '12 02:05

wfbarksdale


2 Answers

Starting Scala 2.13 you might prefer String::toLongOption in order to safely handle Strings 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
like image 199
Xavier Guihot Avatar answered Sep 23 '22 23:09

Xavier Guihot


Casting doesn't work like that in Scala.

You want:

session.get("user_id").toLong
like image 32
Eve Freeman Avatar answered Sep 20 '22 23:09

Eve Freeman