5

Julia 1.7 added the Returns() function which is described as:

Create a callable f such that f(args...; kw...) === value holds.

However, you can get the same results with a regular function that accepts any arguments:

f1 = Returns(99)
f2(args... ; kwargs...) = return 99
f1() === f2()                                       # true
f1("this", 1) === f2("that", 2)                     # true

Is there some other purpose for Returns() other than being a shortcut for creating a function that returns a fixed result? The PDF documentation doesn't explain Returns() at all.

sj95126
  • 6,520
  • 2
  • 15
  • 34

1 Answers1

3

I find Returns quite useful in cases when some API requires a function, but you need a constant value.

Here is an example in combination with DataFrames.jl. Let us take some data frame and add a constant column to it:

julia> using DataFrames

julia> df = DataFrame(x=1:4)
4×1 DataFrame
 Row │ x
     │ Int64
─────┼───────
   1 │     1
   2 │     2
   3 │     3
   4 │     4

julia> transform(df, Returns(1))
4×2 DataFrame
 Row │ x      x1
     │ Int64  Int64
─────┼──────────────
   1 │     1      1
   2 │     2      1
   3 │     3      1
   4 │     4      1

(there are other ways to do this operation, but this shows a case when it is useful to have - the transform function expects a function)

A more advanced aspect of its use is making a closure:

julia> x = [1, 2, 3]
3-element Vector{Int64}:
 1
 2
 3

julia> y = Returns(x)
Returns{Vector{Int64}}([1, 2, 3])

julia> y()
3-element Vector{Int64}:
 1
 2
 3

julia> push!(x, 100)
4-element Vector{Int64}:
   1
   2
   3
 100

julia> y()
4-element Vector{Int64}:
   1
   2
   3
 100

and as you can see return value of y is updated if the underlying vector bound to x is mutated. Note that this capturing is type stable.

See also the discussion in the PR that introduced it and an example usage in this answer on SO.

Bogumił Kamiński
  • 66,844
  • 3
  • 80
  • 107