Thread overview
How to check if something can be null
Jul 01, 2022
Antonio
Jul 01, 2022
Antonio
Jul 01, 2022
user1234
Jul 01, 2022
Adam D Ruppe
Jul 01, 2022
Antonio
July 01, 2022

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

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

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.

void main(){
  doSomething!Json(null);
}

Compiler outputs

Error: incompatible types for (v) is (null): Jsonandtypeof(null)`

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

July 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

July 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:

>

-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:

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.

July 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


July 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:

>

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...