Questions about Union{T,Nothing} and the `something` function (like, when do you use it?)


#1

So, I’ve been reading the docs a lot lately. The FAQ has this crazy thing about nothingness that just raises more questions. I get nothing, and I get Union{T,Nothing} where T and use it frequently. That’s fine. I have two main things I want to know:

There is this sentence:

Note that the compiler is able to generate efficient code when working with Union{T, Nothing} arguments or fields.

That sounds great. Does that work on arrays? can I have efficient arrays of nullable types? Should I be doing something else if I want to preallocate a large array and fill it later? (can I turn Julia into C? :stuck_out_tongue:)


OK, next question. What is this Some and something stuff? I think I understand the conceptual difference between nothing as a value and nothing as the absence of value (I’ve had to write my private “empty” objects in other languages to mark the absence of a value where I’m handling data structures in a library and the API-user’s nil/null/None is a value, as far as the library is concerned)

I understand that something and Some(nothing) are somehow related to these usecases, but I really have no idea exactly how or where to use them. Can someone give an example or two?


#2

Yup, definitely! See https://docs.julialang.org/en/v1/manual/missing/index.html#Arrays-With-Missing-Values-1 (the docs mention Union{T, Missing}, but the same performance results can be obtained for Union{T, Nothing}).

Nope, it’s all the same kind of operation:

julia> x = Array{Union{Int, Nothing}}(undef, 10)
10-element Array{Union{Nothing, Int64},1}:
 nothing
 nothing
 nothing
 nothing
 nothing
 nothing
 nothing
 nothing
 nothing
 nothing

julia> for i in 1:10
         x[i] = i
       end

julia> x
10-element Array{Union{Nothing, Int64},1}:
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10

Yup, that’s pretty much exactly the issue that Some is designed to solve. You would typically write: "there is a value here and that value is nothing" as Some(nothing) and you would write “there is no value here” as simply nothing.

As for something, I think the docs explain it pretty well:

help?> something
search: something

  something(x, y...)

  Return the first value in the arguments which is not equal to nothing, if any. Otherwise throw an error.
  Arguments of type Some are unwrapped.

  Examples
  ≡≡≡≡≡≡≡≡≡≡

  julia> something(nothing, 1)
  1
  
  julia> something(Some(1), nothing)
  1
  
  julia> something(missing, nothing)
  missing
  
  julia> something(nothing, nothing)
  ERROR: ArgumentError: No value arguments present

#3

Thanks so much for the response! very helpful!