Julia Community 🟣

Steven Siew
Steven Siew

Posted on

How to customize existing base Julia functions

How to customize existing base Julia function

Have you ever wish you could create a customize version of an existing Base function.

Here is a simple trick to do it.

julia> myprint(a,b...;kwargs...) = begin print("> "); print(a,b...;kwargs...); end
myprint (generic function with 1 method)

julia> myprint("hello world\n")
> hello world

julia> myprintln(a,b...;kwargs...) = begin print("> "); println(a,b...;kwargs...); end
myprintln (generic function with 1 method)

julia> myprintln("hello ",56.7," world")
> hello 56.7 world
Enter fullscreen mode Exit fullscreen mode

Now you have the functions myprint() and myprintln() which behaves how you wanted it with all the functionality of print() and println()

You can also create it this way

function myprint(a,b...;kwargs...)
    print("> ")
    print(a,b...;kwargs...)
end
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)