我有两个班,Guid和UserGuid。 Guid有一个类型参数。 UserGuid是Guid的一个特例,代表一个没有类的实体(User),所以我把它实现为Guid [Any]。
我有几种Guid应用方法,我想在两种类型之间共享,所以我把它们放在一个超类(GuidFactory)中。但是,由于Guid是参数化的,我必须参数化GuidFactory特征,否则生成的Guid将被参数化为Guid [_]。
因此,我的伴随对象UserGuid无法编译,抱怨:
错误:com.wixpress.framework.scala.UserGuid没有类型参数, 预期:一个对象UserGuid扩展了GuidFactory [UserGuid]
我有什么方法可以在Guid和UserGuid之间共享应用方法,还是我必须复制它们或使用转换?
代码如下。
abstract class TypeSafeId[I, T](val id: I) extends Serializable
class Guid[T](override val id: String) extends TypeSafeId[String, T](id)
class UserGuid(override val id: String) extends Guid[Any](id)
trait GuidFactory[I[A] <: Guid[A]] {
def apply[T](id: String): I[T]
def apply[T](id: UUID): I[T] = apply(id.toString)
def apply[T](ms: Long, ls: Long): I[T] = apply(new UUID(ms, ls))
def apply[T](bytes: Array[Byte]):I[T] = apply(UUID.nameUUIDFromBytes(bytes))
def random[T] = apply[T](UUID.randomUUID())
}
object Guid extends GuidFactory[Guid] {
override def apply[T](id: String) = new Guid[T](id)
}
object UserGuid extends GuidFactory[UserGuid] {
override def apply(id: String) = new UserGuid(id)
}
答案 0 :(得分:2)
这是我能提出的最佳建议:
import java.util.UUID
abstract class TypeSafeId[I, T](val id: I) extends Serializable
class Guid[T](override val id: String) extends TypeSafeId[String, T](id)
class UserGuid(override val id: String) extends Guid[Any](id)
trait GuidFactory[G] {
def apply(id: String): G
def apply(id: UUID): G = apply(id.toString)
def apply(ms: Long, ls: Long): G = apply(new UUID(ms, ls))
def apply(bytes: Array[Byte]): G = apply(UUID.nameUUIDFromBytes(bytes))
def random = apply(UUID.randomUUID())
}
object Guid {
def apply[T] = new GuidFactory[Guid[T]] {
def apply(id: String) = new Guid[T](id)
}
}
object UserGuid extends GuidFactory[UserGuid] {
override def apply(id: String) = new UserGuid(id)
}
val guid1 = Guid[String]("123")
答案 1 :(得分:1)
这会解决您的问题吗?:
package guid
import java.util.UUID
abstract class TypeSafeId[I, T](val id: I) extends Serializable
class Guid[T](override val id: String) extends TypeSafeId[String, T](id)
class UserGuid(override val id: String) extends Guid[Nothing](id)
trait GuidFactory[I[A] <: Guid[A]] {
def apply[T](id: String): I[T]
def apply[T](id: UUID): I[T] = apply(id.toString)
def apply[T](ms: Long, ls: Long): I[T] = apply(new UUID(ms, ls))
def apply[T](bytes: Array[Byte]):I[T] = apply(UUID.nameUUIDFromBytes(bytes))
def random[T] = apply[T](UUID.randomUUID())
}
object Guid extends GuidFactory[Guid] {
override def apply[T](id: String) = new Guid[T](id)
}
//object UserGuid extends GuidFactory[UserGuid] {
// override def apply(id: String) = new UserGuid(id)
//}
object Test {
val guid1 = Guid[String]("123")
val guid2 = Guid.random[List[Any]]
val userguid = Guid("123")
val userguid2 = Guid.random
}