Skip to content

Instantly share code, notes, and snippets.

@bverbeken
Created May 19, 2014 10:24
Show Gist options
  • Save bverbeken/2909060637008a4a7f13 to your computer and use it in GitHub Desktop.
Save bverbeken/2909060637008a4a7f13 to your computer and use it in GitHub Desktop.
How can I avoid duplication here?
object MyImplicits {
implicit def fieldString_To_OptionString(duck: {def getValue(): String}): Option[String] = {
duck match {
case null => None
case x => Option(x.getValue())
}
}
implicit def fieldDecimal_To_OptionOfBigDecimal(duck: {def getValue(): java.math.BigDecimal}): Option[BigDecimal] = {
duck match {
case null => None
case x => Option(x.getValue())
}
}
}
@octonato
Copy link

object MyImplicits {

  private def fieldT_ToOptionT[T](duck: {def getValue(): T}) : Option[T] = {
    duck match {
      case null => None
      case x => Option(x.getValue())
    }
  }

  implicit def fieldString_To_OptionString(duck: {def getValue(): String}) =
    fieldT_ToOptionT[String](duck)  

  implicit def fieldDecimal_To_OptionOfBigDecimal(duck: {def getValue(): java.math.BigDecimal}) =
    fieldT_ToOptionT[java.math.BigDecimal](duck)  

}

@bverbeken
Copy link
Author

Thanks!
Just one tiny problem with this: fieldDecimal_To_OptionOfBigDecimal converts to java.math.BigDecimal, not the scala BigDecimal..
But I get the idea, and you'll get beer next time we meet ;)

@octonato
Copy link

You want the Scala version? In that case, you can't generify it that way. Your output is not the same as your input. You need two type parameters.

ps: yes, beer!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment