I am search for the right signature of a method that takes a function func and an argument arg, copies them over the network to a remote computer and returns the result. Currently the signature looks like this:
def invokeRemote[A,B](address: String, func: A => B, arg: A): B
The problem with this is that the method throws a NotSerializable Exception if the arguments are not Serializable or one of Java’s primitive types.
I came up with the following solution to catch this error at compile time …
type Func = (A => B) with Serializable
def invokeRemote[A <: Serializable, B <: Serializable](address: String, func: Func, arg: A): B
… but now it is not possible anymore to pass arguments of type AnyVal like Int, Float or Double which do not explicitly implement Serializable.
How should the method signature look like such that it accepts only Serializable objects or objects of type AnyVal as argument?
You can use a context bound implicit with a custom trait and provide implicit conversions for
AnyValandSerializableto that trait.The compiler will look for an implicit parameter based on the type and because some are provided for
T <: AnyValandT <: java.io.Serializableit will compile in that case.You can stick the implicit definitions in the companion object for
Serso that they are available where needed.Then, your signature becomes: