get

..  get(f::Function, collection, key)

Return the value stored for the given key, or if no mapping for the key is present, return ``f()``.  Use :func:`get!` to also store the default value in the dictionary.

This is intended to be called using ``do`` block syntax::

  get(dict, key) do
      # default value calculated here
      time()
  end

Examples

julia> dict = ["A"=>1, "B"=>2];

julia> get(dict, "A", 42)
1

julia> get(dict, "C", 42)
42

julia> get(() -> "Hello", dict, "D")
"Hello"

do block syntax

julia> function f(key)
        get(dict,key) do        # dict from above
            reduce(+,[1:10])    # = 1 + 2 + 3 ..
        end
    end;                        
julia> f("B")
2
julia> f("foo")
55
julia> dict = Dict(["one"=> 1, "two"=> 2, "three"=> 3])
       get(dict,"one",5)
1
julia> dict = Dict(["one"=> 1, "two"=> 2, "three"=> 3])
       get(dict,"four",5)
5

The get(x, y) function in Julia is used to access the value of a Nullable{T} object. It attempts to retrieve the value, and if it is present, it returns the value. Otherwise, it returns the provided default value y after converting it to type T. Here are some examples of how to use the get function:

  1. Accessing a non-null value:

    julia> x = Nullable(10)
    Nullable{Int64}(10)
    
    julia> get(x, 0)
    10

    In this example, the Nullable object x contains a non-null value of 10. When using get(x, 0), the function returns the value 10.

  2. Accessing a null value with a default:

    julia> x = Nullable{Int64}()
    
    julia> get(x, 0)
    0

    Here, the Nullable object x does not contain a value. When using get(x, 0), the function returns the default value 0.

  3. Providing a different default value type:

    julia> x = Nullable{Float64}()
    
    julia> get(x, 0.0)
    0.0

    In this case, we use a Nullable object x without a value. However, the default value provided to get(x, 0.0) is of type Float64, which is then converted to the appropriate type.

Common mistake example:

julia> x = Nullable{Int64}()

julia> get(x, "default")
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Int64

In this example, the default value provided to get(x, "default") is of type String, which cannot be converted to Int64. It is important to ensure that the default value type matches the desired type of the Nullable object.

See Also

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: