How to check if something can be null

Antonio antonio at abrevia.net
Fri Jul 1 13:48:25 UTC 2022


I has been using this pattern each time something needs special 
treatment when it can be null:

```d
void doSomething(T)(T v)
{
   import std.traits: isAssignable;
   static if( isAssignable!(T, typeof(null))) {
     if(v is null)
       writeln("This is null");
     else
       writeln("This is not null");
   } else {
     writeln("This can't be null");
   }
}
```

and then

```d
void main(){
   // output: This is null
   doSomething!string(null);
   // output: This is not null
   doSomething("Hello");
   // output: This can't be null
   soSomething!int(1);
}
```

Problem appears with `vibe-d` `Json`.

```d
void main(){
   doSomething!Json(null);
}
```
Compiler outputs

`Error: incompatible types for `(v) is (null)`: `Json` and 
`typeof(null)`

-Why?
-Whats the correct whay to test if something can be null?


More information about the Digitalmars-d-learn mailing list