在模板播放 2.0 模板中将字符串转换为 Scala 中的 Long
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10406859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Casting String to Long in Scala in template play 2.0 template
提问by wfbarksdale
How can I cast from a String to a long in a Scala play 2.0 template?
如何在 Scala play 2.0 模板中从 String 转换为 long?
I want to do the following where I have the action: Application.profile(Long user_id):
我想在我有行动的地方做以下事情Application.profile(Long user_id):
<a href='@routes.Application.profile((Long) session.get("user_id"))'>@session.get("username")</a>
回答by Eve Freeman
Casting doesn't work like that in Scala.
在 Scala 中,转换不是这样工作的。
You want:
你要:
session.get("user_id").toLong
回答by Xavier Guihot
Starting Scala 2.13you might prefer String::toLongOptionin order to safely handle Strings which can't be cast to Long:
开始时,Scala 2.13您可能更喜欢String::toLongOption安全地处理String无法转换为 s 的 s 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::toLongand Try:
对于早期版本,您可以选择混合使用String::toLong和Try:
import scala.util.Try
Try("1234".toLong).getOrElse(-1L) // 1234L
Try("lOZ1".toLong).getOrElse(-1L) // -1L

