rainerhahnekamp
rainerhahnekamp

Reputation: 1136

Scala implicit Long to Serializable

I want to use Scala's Long in Spring's

 AbstractPersistable<PK extends Serializable> 

by using an implicit.

Following example/test does not compile:

class A[+T]

object Helper {
  implicit def sLong(l: scala.Long): java.io.Serializable = scala.Long.box(l)
  val a: A[java.io.Serializable] = new A[Long]
}

and returns

Error:(18, 36) type mismatch;
 found   : com.kiga.db.A[Long]
 required: com.kiga.db.A[java.io.Serializable]
  val a: A[java.io.Serializable] = new A[Long]

Update 1:

It turns out that

implicit def sl(l: A[Long]): A[java.io.Serializable] = new A[java.io.Serializable] 

does the trick, but the Scala translation from AbstractPersistable's code is wrong. It should be:

abstract class AbstractPersistable[PK <: java.io.Serializable]

and I want to achieve following:

class ScalaPersistable extends AbstractPersistable[scala.Long]

Upvotes: 0

Views: 1071

Answers (3)

Odomontois
Odomontois

Reputation: 16318

So combining both answers. As Alexey said, you cannot add interface implementation to a class by implicit conversion, you should use some wrapper to have both serialization and Long value accessible.

As Javier said, conversion between underlying types does not imply conversion between your container type. For such conversion your type should provide something like Functor interface

E.g. you could define your type such way

class A[+T] {
  def map[U](implicit f: T => U): A[U] = ???
}

Now having

val a = new A[Long]

You could use this method like

val jA: A[java.lang.Long] = a.map
val sA: A[SerializableLong] = a.map

Where SerializableLong is taken with conversions from Alexey's answer

Upvotes: 0

Alexey Romanov
Alexey Romanov

Reputation: 170805

An implicit won't make scala.Long extend Serializable. You can either use java.lang.Long or create a class like

case class SerializableLong(x: Long) extends Serializable
object SerializableLong {
  implicit def longToSLong(x: Long) = SerializableLong(x)
  implicit def sLongToLong(x: SerializableLong) = x.x
}

Upvotes: 2

Javier Vargas
Javier Vargas

Reputation: 94

Your implicit converts from Long to java.io.Serializable, and you need an implicit that converts from A[Long] to A[java.io.Serializable]

Upvotes: 1

Related Questions