Casting String to Long in Scala in template play 2.0 template
Asked Answered
A

2

12

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>
Apotropaic answered 2/5, 2012 at 2:14 Comment(0)
B
29

Casting doesn't work like that in Scala.

You want:

session.get("user_id").toLong
Bedroll answered 2/5, 2012 at 2:19 Comment(4)
Oh, well now I feel stupid haha. I got confused with scala's option class.Apotropaic
Don't worry, I was there just a few weeks ago! :)Bedroll
toLong only works on String, but session.get("user_id") returns Option[String]Prosthetics
I had a similar situation, if session.get("user_id") returns Option[String], you can use session.get("user_id").toString.toLongMultiplication
M
1

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
Minimal answered 4/3, 2019 at 21:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.