我有一些用于管理项目中的实体和服务的通用代码,我昨天遇到了一个奇怪的问题。我已经设法缩小了这个:
object Test extends App {
trait Id extends Any {
def id: Int
}
trait EntityWithId[I] {
def id: Option[I]
}
case class UserId(id: Int) extends AnyVal with Id
case class User(id: Option[UserId], password: String) extends EntityWithId[UserId]
trait BaseService[I <: Id, E <: EntityWithId[I]] {
def save(entity: E): I = entity.id.get // mock
}
trait UserService extends BaseService[UserId, User] {
def encrypt(pass: String): String = pass // mock
def encryptAndSave(user: User): UserId =
super.save(user.copy(password = encrypt(user.password)))
}
object UserService extends UserService
val user1 = User(Some(UserId(1)), "jerzy")
val user2 = User(Some(UserId(2)), "jerzy")
UserService.save(user1) // passes
UserService.encryptAndSave(user2) // fails
}
当我尝试使用来自encryptAndSave
的{{1}}方法时,会抛出奇怪的异常:
UserService
我已经设法通过将Exception in thread "main" java.lang.ClassCastException: controllers.Test$UserId cannot be cast to java.lang.Integer
at scala.runtime.BoxesRunTime.unboxToInt(Unknown Source)
at controllers.Test$UserService$.controllers$Test$UserService$$super$save(Test.scala:32)
at controllers.Test$UserService$class.encryptAndSave(Test.scala:29)
at controllers.Test$UserService$.encryptAndSave(Test.scala:32)
at controllers.Test$delayedInit$body.apply(Test.scala:38)
at scala.Function0$class.apply$mcV$sp(Function0.scala:40)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App$$anonfun$main$1.apply(App.scala:71)
at scala.App$$anonfun$main$1.apply(App.scala:71)
at scala.collection.immutable.List.foreach(List.scala:309)
at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:32)
at scala.App$class.main(App.scala:71)
at controllers.Test$.main(Test.scala:8)
at controllers.Test.main(Test.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
更改为super.save()
来解决此问题,但我没有任何线索可解决这个问题。