Option[Int] function parameter impl conv. error with null??

150 views
Skip to first unread message

John K.

unread,
Sep 8, 2012, 12:32:42 PM9/8/12
to scala...@googlegroups.com
[Scala 2.9.1]
I am creating a function that takes an Option[Int] as one of its parameters, as this parameter maybe null...

Here is what is happening...

scala> def nullTest(n:Option[Int]) = n.getOrElse(0)
nullTest: (n: Option[Int])Int

scala> nullTest(Option(null))

<console>:9: error: type mismatch;
 found   : Null(null)
 required: Int
Note that implicit conversions are not applicable because they are ambiguous:
 both method Integer2intNullConflict in class LowPriorityImplicits of type (x: Null)Int
 and method Integer2int in object Predef of type (x: java.lang.Integer)Int
 are possible conversion functions from Null(null) to Int
              nullTest(Option(null))


So how can i create a Option[Int] parameter that maybe null?

FYI, This does work using a String.
IE.
scala> def nullTest(n:Option[String]) = n.getOrElse("I got Nothing")
nullTest: (n: Option[String])String

scala> nullTest(Option(null))
res20: String = I got Nothing

Rex Kerr

unread,
Sep 8, 2012, 12:39:18 PM9/8/12
to John K., scala...@googlegroups.com
Int is a primitive type, so
  val i : Int = null
doesn't exactly make sense.

I suspect that you're just trying to represent that the integer doesn't exist.  In that case, use None instead of Option[Int](null).

(None is the universal empty option.)

  --Rex

Lanny Ripple

unread,
Sep 9, 2012, 1:52:02 PM9/9/12
to scala...@googlegroups.com
You can cast null as any of the basic types

scala> def nullTest(n:Option[Int]) = n.getOrElse(0)
nullTest: (n: Option[Int])Int

scala> nullTest(Option(null.asInstanceOf[Int]))
res1: Int = 0

Note that for primitive types you'll get the "zero"

scala> null.asInstanceOf[Boolean]
res2: Boolean = false

scala> null.asInstanceOf[Char]
res3: Char = ?

scala> res3.toInt
res4: Int = 0

And for Object's you'll just get null

scala> null.asInstanceOf[String]
res5: String = null

I find it interesting that even though the zero acts correctly

scala> null.asInstanceOf[Int] + 3
res6: Int = 3

It's still a null by value

scala> Option(null.asInstanceOf[Int])
res7: Option[Int] = None
Reply all
Reply to author
Forward
0 new messages