scalagenericsimplicit-conversionserializablescala-generics

Extending generic Serializables with implicit conversions


I am trying to add extensions methods to Serializable 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) = {
    println(msg)
    assert(s.isInstanceOf[Serializable])
  }
}

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")
y.isSer("Serializable")
ly.isSer("list of Serializable")

List extends Serializable

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


Solution

  • 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.