digitalmars.D.learn - How to check if something can be null
- Antonio (38/38) Jul 01 2022 I has been using this pattern each time something needs special
- Antonio (5/7) Jul 01 2022 I realized Json is an struct (not an object)... and I supose, it
- user1234 (8/15) Jul 01 2022 Something like this does the job:
- Adam D Ruppe (4/6) Jul 01 2022 i'd prolly check `static if(is(typeof(null) : T))` which means if
- Antonio (4/10) Jul 01 2022 love it X-) !!! may be this is the Swiss knife I was waiting
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
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
On Friday, 1 July 2022 at 13:53:28 UTC, Antonio wrote:On Friday, 1 July 2022 at 13:48:25 UTC, Antonio wrote: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.-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
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
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:Perfect!!! Thanks Adam.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 lollove it X-) !!! may be this is the Swiss knife I was waiting for...
Jul 01 2022