jido
November 21, 2022, 8:12pm
1
Is there a way to tell the compiler that really, it is OK?
I wrote this code:
let result = isTitle(line)
if result->Array.length == 2 {
let [_, title] = result // TODO: silence warning
Js.log("TITLE: " ++ title)
}
The compiler replies:
Warning 8: You forgot to handle a possible case here, for example:
[]
And the generated code contains:
var result$1 = isTitle(line);
if (result$1.length === 2) {
if (result$1.length !== 2) {
throw {
RE_EXN_ID: "Match_failure",
I tried using @@warning but that is not recognised.
DZakh
November 21, 2022, 9:10pm
2
There’s a way to work around the error:
switch isTitle(line) {
| [_, title] => Js.log("TITLE: " ++ title)
| _ => ()
}
And the generated code will be:
var match = isTitle(line);
if (match.length === 2) {
var title = match[1];
console.log("TITLE: " + title);
}
1 Like
fham
November 21, 2022, 10:00pm
3
Deactivating the warning should work fine, but you set it for a range of lines, not a single line.
@@warning("-8")
let result = isTitle(line)
if result->Array.length == 2 {
let [_, title] = result
Js.log("TITLE: " ++ title)
}
@@warning("+8")
If you omit the @@warning("+8")
, the warning is disabled for the rest of the file.
Playground link
But you rather should write something similar to DZahk’s suggestion. While you can easily pattern-match on tuples or records just with a let-binding, it does not work without warnings where there are other possible permutations that your match misses, like arrays or lists. For such data structures you should prefer using switch
.