oftype
oftype(x, y)
Convert y to the type of x (convert(typeof(x), y)).
Examples
In the Julia programming language, the function oftype(x, y) is used to convert y to the type of x using the convert function (convert(typeof(x), y)). Here are some examples of its usage:
-
Convert an integer to a float:
julia> oftype(3.14, 5) 5.0This example converts the integer
5to a float, matching the type of3.14. -
Convert a string to an integer:
julia> oftype(10, "42") 42Here, the string
"42"is converted to an integer, matching the type of10. - Convert an array of integers to an array of floats:
julia> oftype([1, 2, 3, 4], Float64) 4-element Array{Float64,1}: 1.0 2.0 3.0 4.0This example converts each element of the array
[1, 2, 3, 4]to a float, resulting in a new array of typeFloat64.
Common mistake example:
julia> oftype(2, "hello")
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Int64
In this example, the function oftype fails because it attempts to convert a string "hello" to an integer Int64, which is not possible. Ensure that the types are compatible for successful conversion using oftype.
See Also
base, big, bytes2hex, cconvert, complex, convert, dec, hex, hex2bytes, hex2num, oct, oftype, parse, promote, signed, unsafe_convert, unsigned, widen,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.