How to cast Long to Int in Scala?

46,918

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

Share:
46,918
Ivan
Author by

Ivan

Updated on July 09, 2022

Comments

  • Ivan
    Ivan almost 2 years

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

    
    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.

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

  • Eugene Yokota
    Eugene Yokota over 12 years
    .toInt is better than asInstanceOf[Int]. what was I thinking.
  • Ivan
    Ivan over 12 years
    Looks like it works. Compiles at least. Perhaps I need to have some sleep... :-]
  • Ivan
    Ivan over 12 years
    @eugene-yokota, would you be so kind to explain why is .toInt better than asInstanceOf[Int]? Intuitively it seems obvious, but I am curious to know.
  • Eugene Yokota
    Eugene Yokota over 12 years
    @Ivan, because toInt is still within the means of Scala standard library (and hopefully with good optimizations and checking etc) whereas asInstanceOf is like opening the emergency escape hatch while the plane is in midair.
  • Luigi Plinge
    Luigi Plinge over 12 years
    @Ivan casts are inherently not typesafe. E.g. class Foo; (new Foo).asInstanceOf[Int] compiles, but throws a ClassCastException at runtime. So using a cast, you're losing the benefit of static type checking at compile time.
  • Scott Carey
    Scott Carey over 9 years
    Yes, but is it efficient, or does it box?
  • Luigi Plinge
    Luigi Plinge over 9 years
    @ScottCarey yes it is efficient. These enrichments (RichLong etc) are value classes, so effectively you're using a static method. You can rely on the Scala library writers to have thought of this kind of thing.
  • raisercostin
    raisercostin over 9 years
    Does it throw an exception for values bigger than Integer.MAX_VALUE? Something like guava's Ints.checkedCast(long) ? - docs.guava-libraries.googlecode.com/git/javadoc/com/google/…
  • Luigi Plinge
    Luigi Plinge over 9 years
    @raisercostin No it does not. In that respect it follows all other Java arithmetic, i.e. bounds-checking is sacrificed for performance. However it's trivial to write such a method yourself.