【问题标题】:Why is this field validation a type mismatch?为什么此字段验证类型不匹配?
【发布时间】:2022-01-13 15:15:20
【问题描述】:

我很难理解为什么 scala 会让我愉快地写一些字段验证:

field -> text().verifying("declaration.additionalDocument.documentTypeCode.unacceptableCode", f => isEmpty(f) or !documentCodesNotAcceptable.contains(f))

但当我这样做时不会:

text().verifying("declaration.additionalDocument.documentTypeCode.unacceptableCode", isEmpty or !documentCodesNotAcceptable.contains(_))

在第二种情况下,我收到一个编译错误,告诉我type mismatch; found : String => Boolean required: Boolean

但是为什么呢?第二种方式和第一种方式有什么不同?

【问题讨论】:

  • 因为第二个扩展为isEmpty.or(x => !documentCodesNotAcceptable.contains(x)) 这就是为什么_ 语法在我的黑名单中,
  • @LuisMiguelMejíaSuárez 我明白了。所以我假设x => !documentCodesNotAcceptable.contains(x) 没有解析为布尔值,因为x 没有价值?
  • 不,比这更简单。 or 期望 Boolean 而不是 Function 无论如何 Function returns.
  • @LuisMiguelMejíaSuárez 啊,我现在明白了。此外,我能否要求澄清一下您为什么不喜欢 _ 语法 - 您总是更喜欢匿名函数吗?
  • 我不喜欢这种问题,人们对此感到困惑,或者他们有工作代码并进行了一些小改动,然后它会因奇怪的类型错误而失败。所以我通常更喜欢 lambda,但当 lambda 太小时,我会使用 _,例如 foos.map(_.bar)foo.reduce(_ + _)

标签: scala types


【解决方案1】:

verifying 的第二个参数似乎是一个谓词。即接受一个值并返回truefalse 的函数,这是验证框架的常见特性。

在第一个例子中,谓词是

f => isEmpty(f) or !documentCodesNotAcceptable.contains(f)

解析为

f => (isEmpty(f) or !documentCodesNotAcceptable.contains(f))

这是一个完全合理的谓词,它首先用isEmpty 测试f,如果失败,则进行第二次测试。

在第二个例子中,谓词是这样的:

isEmpty or !documentCodesNotAcceptable.contains(_)

其中(如 cmets 中所述)扩展为

(x => isEmpty(x)) or (x => !documentCodesNotAcceptable.contains(x))

所以这个表达式试图or 两个函数一起使用,这是不支持的。

解决方案是使用第一个版本:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 2010-12-13
    • 1970-01-01
    • 2013-05-19
    • 2016-01-05
    相关资源
    最近更新 更多