www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to check if something can be null

reply Antonio <antonio abrevia.net> writes:
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?
Jul 01 2022
next sibling parent reply Antonio <antonio abrevia.net> writes:
On Friday, 1 July 2022 at 13:48:25 UTC, Antonio wrote:
 -Why?
I realized Json is an struct (not an object)... and I supose, it is managing null asignation manually (as a way to build Json(null)).
 -Whats the correct whay to test if something can be null?
That's my question :-p
Jul 01 2022
parent user1234 <user1234 12.de> writes:
On Friday, 1 July 2022 at 13:53:28 UTC, Antonio wrote:
 On Friday, 1 July 2022 at 13:48:25 UTC, Antonio wrote:
 -Why?
I realized Json is an struct (not an object)... and I supose, it is managing null asignation manually (as a way to build Json(null)).
 -Whats the correct whay to test if something can be null?
That's my question :-p
Something like this does the job: ```d enum canBeNull(T) = is(typeof({T t; t = null;})); static assert(canBeNull!(Object)); static assert(!canBeNull!(int)); ``` and that should handle opAssign and opCmp overloads.
Jul 01 2022
prev sibling parent reply Adam D Ruppe <destructionator gmail.com> writes:
On Friday, 1 July 2022 at 13:48:25 UTC, Antonio wrote:
 I has been using this pattern each time something needs special 
 treatment when it can be null:
i'd prolly check `static if(is(typeof(null) : T))` which means if the null literal implicitly converts to type T. there's also the bludgeon __traits(compiles, v is null) too lol
Jul 01 2022
parent Antonio <antonio abrevia.net> writes:
On Friday, 1 July 2022 at 15:35:00 UTC, Adam D Ruppe wrote:
 On Friday, 1 July 2022 at 13:48:25 UTC, Antonio wrote:
 I has been using this pattern each time something needs 
 special treatment when it can be null:
i'd prolly check `static if(is(typeof(null) : T))` which means if the null literal implicitly converts to type T.
Perfect!!! Thanks Adam.
 there's also the bludgeon __traits(compiles, v is null) too lol
love it X-) !!! may be this is the Swiss knife I was waiting for...
Jul 01 2022