Reputation: 47
Does AnyVal (Int, Double) extend scala.Serializable and what is the different between java.io.Serializable and scala.Serializable as a method parameter in Scala?
def f (p : scala.Serializable): Unit = {}
def g (p : java.io.Serializable): Unit = {}
//f(1) Type mismatch, expected:Serializable,actual:Int
g(1) //It works
The Scala doc says that Int is a subType of scala.Serializable(http://www.scala-lang.org/api/2.10.6/index.html#scala.Serializable).However,scala.Serializable extends java.io.Serializable. so I think the value of Int is kind type of scala.Serializable and java.io.Serializable and both can be the parameter above.
Thanks.
Upvotes: 1
Views: 599
Reputation: 2480
Actually Int
does not extend Serializable. The link (from known subclasses) is this one which is just an Ordering[Int]
implicit instance. Int
and AnyVal
are defined like so:
final abstract class Int private extends AnyVal
abstract class AnyVal extends Any
So as you can see, they're not java.io.Serializable
or scala.Serializable
.
As for why the code works, check out scala.Predef
to find the implicit conversion from scala.Int
to java.lang.Integer
(which implements java.io.Serializable
). And scala.Predef
is imported implicitly so that's why it works:
object Predef {
...
implicit def int2Integer(x: Int) = java.lang.Integer.valueOf(x)
...
}
So behind the scene your code is the following:
g(1)
// After the implicit conversion g(1) is actually:
g(Integer.valueOf(1))
I hope this clears up the confusion, I've been there myself :)
Upvotes: 2