我正在尝试定义 atrait Required
来封装逻辑以验证 requiredRecord
Field
的存在,但是,我无法弄清楚 self 类型应该是什么。我的目标是能够写出尽可能接近 eg 的东西object foo extends SomeField(...) with Required
,但是我确实意识到我可能必须明确地将某些类型参数传递给Required
.
到目前为止,我的无能是:
导入 net.liftweb.record.Field 导入 net.liftweb.util.FieldError
trait Required[ThisType, OwnerType] {
this: Field[ThisType, OwnerType] =>
def errMsg = "is required"
override def validations = {
val required =
(x: String) => if (x.isEmpty) List(FieldError(this, errMsg)) else Nil
// this asInstanceOf call also seems fishy
// --why's it even required if we already have the self type in place?
required :: super.asInstanceOf[Field[ThisType, OwnerType]].validations
}
}
但是,这会导致与存在类型相关的编译错误和警告:
myfield = object SomeField(...) with Required[SomeField[SomeModel], SomeModel]
更不用说它从简洁中得到with Required
。
编辑:
我想出了这个:
trait Required[OwnerType] extends Field[String, OwnerType] {
def errMsg = "is required"
override def validations = {
val required =
(x: String) => if (x.isEmpty) List(FieldError(this, errMsg)) else Nil
required :: super.validations
}
}
但是,它不允许我预先required
考虑,super.validations
因为它期望this.type.ValueType => List[FieldError]
not String => List[FieldError]
,我觉得这很奇怪,因为在Field[String, ...]
, ValueType
is String
的情况下。
如果我更改required
为 be ValueType => ...
,它会编译,但会with Required[SomeModel]
出现以下错误:
类型参数 [String,OwnerType] 不符合 trait 字段的类型参数界限 [ThisType,OwnerType <: net.liftweb.record.Record[OwnerType]]
...即使StringField.ThisType
是String
并且String.OwnerType
是 的子类Record[SomeModel]
,SomeModel
是 的子类MongoRecord[SomeModel]
。-我迷路了。