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:
-
Accessing a non-null value:
julia> x = Nullable(10) Nullable{Int64}(10) julia> get(x, 0) 10
In this example, the
Nullable
objectx
contains a non-null value of10
. When usingget(x, 0)
, the function returns the value10
. -
Accessing a null value with a default:
julia> x = Nullable{Int64}() julia> get(x, 0) 0
Here, the
Nullable
objectx
does not contain a value. When usingget(x, 0)
, the function returns the default value0
. -
Providing a different default value type:
julia> x = Nullable{Float64}() julia> get(x, 0.0) 0.0
In this case, we use a
Nullable
objectx
without a value. However, the default value provided toget(x, 0.0)
is of typeFloat64
, 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.