Last active
January 23, 2022 23:15
-
-
Save frgomes/c6bf34eeb5ae1769b072 to your computer and use it in GitHub Desktop.
Scala - Converts Any to Double, to LocalDate and Date
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this flavour is pure magic... | |
def toDouble: (Any) => Double = { case i: Int => i case f: Float => f case d: Double => d } | |
// whilst this flavour is longer but you are in full control... | |
object any2Double extends Function[Any,Double] { | |
def apply(any: Any): Double = | |
any match { case i: Int => i case f: Float => f case d: Double => d } | |
} | |
// like when you can invoke any2Double from another similar conversion... | |
import java.time.{LocalDate, ZoneId} | |
object any2LocalDateExcel extends Function[Any,LocalDate] { | |
def apply(any: Any): LocalDate = | |
LocalDate.ofEpochDay(0).plusDays(any2Double(any).intValue-25569) | |
} | |
// and again... | |
import java.util.Date | |
object any2DateExcel extends Function[Any,Date] { | |
def apply(any: Any): Date = | |
Date.from(any2LocalDateExcel(any).atStartOfDay(ZoneId.systemDefault()).toInstant()) | |
} |
Very Usefull!
Very Usefull! so cool thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks to StackOverflow:
http://stackoverflow.com/questions/20691388/using-asinstanceof-to-convert-any-to-double
Bugs:
https://issues.scala-lang.org/browse/SI-1448
https://issues.scala-lang.org/browse/SI-4437