1

我正在尝试定义 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.ThisTypeString并且String.OwnerType是 的子类Record[SomeModel]SomeModel是 的子类MongoRecord[SomeModel]。-我迷路了。

PS 这与电梯记录有关:必填字段的值为空,但没有验证错误

4

1 回答 1

1

以下在 SBT 控制台中编译。

import net.liftweb.util._
import net.liftweb.record._
import net.liftweb.record.field._

trait Required extends StringTypedField {

  override def validations: List[ValidationFunction] = valMinLen(1, "Required!") _ :: super.validations

}

class TestRecord extends Record[TestRecord] {

    val meta = TestRecord

    object testField extends StringField(this, 255) with Required

}

object TestRecord extends TestRecord with MetaRecord[TestRecord]
于 2014-03-14T19:26:59.807 回答