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

Iva*_*van 34 int types casting scala long-integer

我想使用以下函数将Joda Time转换为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
}
Run Code Online (Sandbox Code Playgroud)

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

而且我很难让Scala从长值中创建一个Int.怎么做这样的演员?

Lui*_*hys 62

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

  • @Ivan casts本质上不是类型安全的.例如`class Foo; (new Foo).asInstanceOf [Int]`编译,但在运行时抛出`ClassCastException`.因此,使用强制转换,您将在编译时失去静态类型检查的好处. (10认同)
  • @Ivan,因为`toInt`仍然在Scala标准库的手段内(并且希望有很好的优化和检查等),而`asInstanceOf`就像打开紧急逃生舱,而飞机在半空中. (4认同)