Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override Predef's implicit conversions

Tags:

scala

I have multiple methods that return a java.lang.Integer, which is then implicitly converted to an Int using Scala's Predef implicit conversions, here is how it is written there:

implicit def Integer2int(x: java.lang.Integer): Int = x.intValue

This conversion is not satisfying to me, I would like something along the lines of:

implicit def Integer2int(x: java.lang.Integer): Int = 
  Option(x).getOrElse(new Integer(0)).intValue

as the Integer can sometimes be null and in that case Predef's implicit conversion returns null as well and I would like it to be 0 instead.

I wrote my own conversion but I keep getting errors saying that this declaration is ambiguous given that it is already declared in Predef.

My question is, is there a way to actually override Predef's implicit conversions?

like image 657
Peter Avatar asked May 22 '14 20:05

Peter


1 Answers

You can disable the Predef import like this:

import scala.Predef.{Integer2int => _}

And then just redefine Integer2int as you wish.

Funny proof: http://ideone.com/R7Zyfd

like image 161
tkroman Avatar answered Oct 04 '22 09:10

tkroman