Home > Software engineering >  Why is this field validation a type mismatch?
Why is this field validation a type mismatch?

Time:12-10

I am having trouble understanding why scala will let me write some field validation happily with this:

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

But not when I do this:

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

In the second case I get a compilation error telling me type mismatch; found : String => Boolean required: Boolean

But why? How is the second way different from the first?

CodePudding user response:

The second argument to verifying appears to be a predicate. That is, a function that takes a value and returns true or false, which is a common feature of validation frameworks.

In the first example the predicate is

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

which parses as

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

This is a perfectly reasonable predicate that first tests f with isEmpty and if that fails, does the second test.

In the second example the predicate is this:

isEmpty or !documentCodesNotAcceptable.contains(_)

which (as explained in the comments) expands to

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

So this expression is trying to or two functions together, which isn't supported.

The solution is to go with the first version :)

  • Related