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