Сannot producer expected type

1) How does type casting work?

Sample:
var result: ?Text = List.last(texts);
result - can be zero and real

Next code check

if(result != null){
var resultNotNull: Text = res; - Not work
//~My code
 /*

*/

// DebugProject.print(resNotNull);     
// DebugProject.print(debug_show(resNotNull));
}
else{
//~My code
 /*

*/

// DebugProject.print(info);     
// DebugProject.print(debug_show(info));
};

2) How to convert from a variable of type Nat to type Text?

let digit: Nat = 1;
let toStr: Text = digit.toText; - Error

(expected object type, but expression produces type Nat)

  1. You need to switch and pattern-match on the optional value:
switch result {
  case (?val) { .../* val : Text here*/... };
  case null { ... };
}

If you have multiple of such tests, take a look at the do? construct, which comes in handy and e.g. allows collapsing multiple switches into one:

let result = do? { List.last(list1)! + List.last(list2)! + 1 };
switch result {
  case (?n) { ... handle result ... }
  case null { ... handle error ... }
}

The ! operator inside a do? block converts ?T to T and returns null to the enclosing do? otherwise.

  1. There are library functions for pretty-printing values of number types:
import Nat "mo:base/Nat";
let str = Nat.toText(1);
3 Likes

Ok, thanks for the answer. :wink: