Casting String to Long in Scala in template play 2.0 template

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

Casting doesn't work like that in Scala.

You want:

session.get("user_id").toLong