d money d money - 8 months ago 76
Scala Question

Extending generic Serializables with implicit conversions

I am trying to add extensions methods to

types and there seems to be a hole in my understanding of the class. Here is a snippet of the basics of what I'm trying to do:

class YesSer extends Serializable

class NoSer

implicit class SerOps[S <: Serializable](s: S) {
def isSer(msg: String) = {

val n = new NoSer
val ln = List(new NoSer, new NoSer)
val y = new YesSer
val ly = List(new YesSer, new YesSer)
// n.isSer("non Serializable")
ln.isSer("list of non Serializable")
ly.isSer("list of Serializable")


It's obvious to me the line
won't compile, but it also seems that
also shouldn't compile, as its "inner" type is NoSer. Is there some kind of coercion to
of the inner type of
? Am I trying to do something absolutely bonkers??

Answer Source

List extends Serializable. So List[A].isSer(String) is defined; the type of A does not matter.

Serializable is just a marker interface, used to indicate whether a class is designed to be serializable. Whether or not you will be able to actually serialize the object depends on whether the entire transitive object graph rooted at the object is serializable. Your ln will fail serialization at runtime with a NotSerializableException because it contains non-serializable types. See the javadoc for java.lang.Serializable (which scala.Serializable extends) for more details.