Julia Language Cross-Version Compatibility Using Compat.jl

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

The Compat.jl package enables using some new Julia features and syntax with older versions of Julia. Its features are documented on its README, but a summary of useful applications is given below.

0.5.0

Unified String type

In Julia v0.4, there were many different types of strings. This system was considered overly complex and confusing, so in Julia v0.5, there remains only the String type. Compat allows using the String type and constructor on version 0.4, under the name Compat.String. For example, this v0.5 code

buf = IOBuffer()
println(buf, "Hello World!")
String(buf)  # "Hello World!\n"

can be directly translated to this code, which works on both v0.5 and v0.4:

using Compat
buf = IOBuffer()
println(buf, "Hello World!")
Compat.String(buf)  # "Hello World!\n"

Note that there are some caveats.

  • On v0.4, Compat.String is typealiased to ByteString, which is Union{ASCIIString, UTF8String}. Thus, types with String fields will not be type stable. In these situations, Compat.UTF8String is advised, as it will mean String on v0.5, and UTF8String on v0.4, both of which are concrete types.
  • One has to be careful to use Compat.String or import Compat: String, because String itself has a meaning on v0.4: it is a deprecated alias for AbstractString. A sign that String was accidentally used instead of Compat.String is if at any point, the following warnings appear:
WARNING: Base.String is deprecated, use AbstractString instead.
  likely near no file:0
WARNING: Base.String is deprecated, use AbstractString instead.
  likely near no file:0

Compact broadcasting syntax

Julia v0.5 introduces syntactic sugar for broadcast. The syntax

f.(x, y)

is lowered to broadcast(f, x, y). Examples of using this syntax include sin.([1, 2, 3]) to take the sine of multiple numbers at once.

On v0.5, the syntax can be used directly:

julia> sin.([1.0, 2.0, 3.0])
3-element Array{Float64,1}:
 0.841471
 0.909297
 0.14112 

However, if we try the same on v0.4, we get an error:

julia> sin.([1.0, 2.0, 3.0])
ERROR: TypeError: getfield: expected Symbol, got Array{Float64,1}

Luckily, Compat makes this new syntax usable from v0.4 also. Once again, we add using Compat. This time, we surround the expression with the @compat macro:

julia> using Compat

julia> @compat sin.([1.0, 2.0, 3.0])
3-element Array{Float64,1}:
 0.841471
 0.909297
 0.14112 


Got any Julia Language Question?