Check for null values returned from forA

How can we check for null values in the below snippet?

[data1, data2] <- forA parties (\p -> do return (abc))

data1 and data2 are of record datatype. I want to make sure that these record type data1 and data2 are not null.

How can I achieve this?

1 Like

Daml values do not have an implicit null. If you have something of type a, it can never be null. If a value can be absent this is encoded explicitly via Optional a. In that case, you can do the equivalent of a null-check via a pattern match, e.g.,

case data1 of
  None -> _ -- "do something here"
  Some d -> _ -- "do something here with d"

To put this another way, the pattern [data1, data2] will not match if the list in question does not have exactly two elements.

Other languages have looser requirements here, which you may be thinking of. For example, I believe that if you do this destructuring in TypeScript or Common Lisp it will simply attach undefined or NIL to the extra variables. But in Daml, if a variable is bound, it 100% refers to a valid value of the variable’s type, and will never fail when referenced. So you can count on that being true for all patterns: if there isn’t a value to put there, the pattern will not succeed at all.

Putting a pattern on the left side of a <- has special error reporting behavior; in Daml, typically the transaction is aborted. Execution never proceeds with the next line, because that would violate the rule about variables in Daml. Here’s how a pattern like yours would fail in an Update, such as defined for a choice:

 Aborted:  Pattern match failure in do expression at </path/to/filename>.daml:56:8-10

@cocreature @Stephen Thanks for your reply

Can you provide more snippets or examples with Optional ?

1 Like

I recommend taking a look at the section on variants in the daml intro.

1 Like