Home > Enterprise >  Does a method exist to check if a variable is Nothing or WhiteSpace?
Does a method exist to check if a variable is Nothing or WhiteSpace?

Time:06-04

C# has String.IsNullOrWhiteSpace(String), do we have a IsNothingOrWhiteSpace(String)?

CodePudding user response:

A slightly more elegant way than the other answer would be to fully use the multiple dispatch:

isNullOrWS(::Type{Nothing}) = true
isNullOrWS(::Nothing) = true
isNullOrWS(verify::AbstractString) = isempty(strip(verify))
isNullOrWS(::Any) = false

This actually results also in a faster assembly code.

julia> dat = fill(Nothing, 100);

julia> @btime isNullOrWS.($dat);
  174.409 ns (2 allocations: 112 bytes)

julia> @btime IsNullOrWhiteSpace.($dat);
  488.205 ns (2 allocations: 112 bytes)

CodePudding user response:

I've searched the documentation and it doesn't seem to exist, but you can write it yourself.

function IsNullOrWhiteSpace(verify::Any)
  # If verify is nothing, then the left side will return true.
  # If verify is Nothing, then the right side will be true. 
  return isnothing(verify) || isa(nothing,verify)
end 

function IsNullOrWhiteSpace(verify::AbstractString)
  return isempty(strip(verify))
end

println(IsNullOrWhiteSpace(nothing)) # true
println(IsNullOrWhiteSpace(" ")) # true

Might not be the best way to do it, but it works.

Why do we need both isnothing() and isa()?

Let's see what will happen when we use isnothing() with nothing and Nothing.

println(isnothing(nothing)) # true
println(isnothing(Nothing)) # false

We obviously want to handle Nothing, how do we do it?

Using isa(), it will test if nothing is a type of Nothing.

  • Related