Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Julia can be empty type


May 14, 2021 Julia


Table of contents


Can be empty type

In many cases, you may encounter variables that may or may not exist. T o handle this situation, Julia provides a Nullable{T} which can be considered a special container with 0 or 1 data. Nullable{T} interface to ensure that operations that may be empty values are safe. There are currently four operations:

  • Create a Nullable object.
  • Check Nullable contains data.
  • Gets Nullable and if no data can be returned, NullException .
  • Gets Nullable if no data can be returned, returns the default value of data type T

Create Nullable object

Create an empty object about type T using T the Nullable{T}() function:

   x1 = Nullable{Int}()
   x2 = Nullable{Float64}()
   x3 = Nullable{Vector{Int}}()

Use Nullable(x::T) function to create a non-empty empty object about type T

x1 = Nullable(1)
x2 = NUllable(1.0)
x3 = Nullalbe([1, 2, 3])

Note the difference between the two ways in which empty objects can be constructed above: for the first way, the function accepts the argument as T In another way, the function accepts a single argument, the type of which is T .

Check Nullabe object contains data

Use isnull function to check Nullable object is empty:

   isnull(Nullable{Float64}())
   isnull(Nullable(0.0))

Securely access the Nullable object

Use get to securely access the Nullable object:

   get(Nullable{Float64}())
   get(Nullable(1.0))

If there is no data, Nullable{Float64} NullException error. get function guarantees that any operation that accesses data that does not exist throws an error immediately.

In some Nullable object is empty, we want to return a reasonable default value. We can pass this default value to get function as the second argument:

  get(Nullable{Float64}(), 0)
   get(Nullable(1.0), 0)

Note that this default parameter is automatically converted to type T F or example, in the example above, get automatically 0 Float64 before the Float64 get function can set the default replacement value, which makes it easy to handle undefined variables.