如何在 Scala 中将 Long 转换为 Int?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7782502/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:35:24  来源:igfitidea点击:

How to cast Long to Int in Scala?

scalatypescastingintlong-integer

提问by Ivan

I'd like to use the folowing function to convert from Joda Time to Unix timestamp:

我想使用以下函数将 Joda 时间转换为 Unix 时间戳:


def toUnixTimeStamp(dt : DateTime) : Int = {
  val millis = dt.getMillis
  val seconds = if(millis % 1000 == 0) millis / 1000
    else { throw new IllegalArgumentException ("Too precise timestamp") }

  if (seconds > 2147483647) {
    throw new IllegalArgumentException ("Timestamp out of range")
  }

  seconds
}

Time values I intend to get are never expected to be millisecond-precise, they are second-precise UTC by contract and are to be further stored (in a MySQL DB) as Int, standard Unix timestamps are our company standard for time records. But Joda Time only provides getMillis and not getSeconds, so I have to get a Long millisecond-precise timestamp and divide it by 1000 to produce a standard Unix timestamp.

我打算获得的时间值永远不会精确到毫秒,它们是合约上精确到秒的 UTC 并且将进一步存储(在 MySQL 数据库中)作为 Int,标准 Unix 时间戳是我们公司的时间记录标准。但是 Joda Time 只提供 getMillis 而不是 getSeconds,所以我必须得到一个 Long 毫秒级的时间戳并将它除以 1000 以生成一个标准的 Unix 时间戳。

And I am stuck making Scala to make an Int out of a Long value. How to do such a cast?

我坚持让 Scala 从 Long 值中生成一个 Int 。这样的演员怎么演?

回答by Luigi Plinge

Use the .toIntmethod on Long, i.e. seconds.toInt

使用.toIntLong上的方法,即seconds.toInt