Assigning a variable to "null"

Could someone quickly educate me on why assigning my typed variable to “null” is prohibited here:

var selectedTicket : Ticket = null;

returns the following error:

main.mo:194.39-194.43: type error [M0050], literal of 
type Null does not have expected type
{
name : Name;
qrCode : QRCode;
tokenIndex : TokenIndex/1;
user : AccountIdentifier/2
}

My overall goal is to set the variable to “null” at the begining of my function, then update it when I have found the desired object.

Could anyone explain why I get this error and what other approach I should take to instantiate a variable at the top of my function, then update it later?

Many thanks in advance!

You need to make your type optional, this way you can assign null.

var selectedTicket : ?Ticket = null;

More info:

1 Like

Thanks for the feedback. Instantiating that way (var selectedTicket : ?Ticket = null;), lead to the following error when I assign the variable to the strict type Ticket later:

/main.mo:209.51-209.57: type error [M0096], expression of type
{
name : Name;
qrCode : QRCode;
tokenIndex : TokenIndex/1;
user : AccountIdentifier/2
}
cannot produce expected type
?Ticket

It seems backwards to edit the type Ticket to be optional to accomodate a logistical situation like this…From trial and error, I have learned that a switch statement unwraps a optional type into a normal type…is there a way to do this without using a switch statement?

Well I solved it by trial and error, it turns out I had to make the assignment like so:

selectedTicket := ?ticket;

My immediate problem is solved, but now I have to deal with the type ?Ticket for the rest of my program, which is unecessary…How could I unwrap a optional type into a normal type (like a switch statement seems to do, but without using a switch statement)?

Thanks all!