Is it possible to use "supertype" in function type declaration

Hi,

When I process strings in Julia, I have often a problem with the ::String type because sometime my function need a String and sometime a SubString{String} and I have this error

no method matching processData(::SubString{String})

A quick (and dirty) solution to solve this issue is to avoid type declaration, for example, replace

processData(data::String)
by
processData(data)

But this is not optimal for performances. Of course it is possible to use multiple dispatch and write 2 functions

processData(::SubString{String})
processData(::String)

This is a simple example, but imagine that I have a function which process 10 strings that could also be SubString{String}, it is not possible to write all functions with all types combinations. So I wonder if there is a more efficient solution, if it would be possible to use a supertype in function declaration, something like

processData(<:String)

Thanks ! :wink:

This does not impact performance at all.

Anyway, here, you would do:

processData(::AbstractString)

because

julia> supertype(String)
AbstractString

This function would accept anything that is <: AbstractString.

2 Likes

Thank you very much for your quick answer @kristoffer.carlsson

I delcare types in Julia, because in performance tips it is said : “Julia’s compiler specializes code for argument types at function boundaries, so in the original implementation it does not know the type of a during the loop (since it is chosen randomly). Therefore the second version is generally faster since the inner loop can be recompiled as part of fill_twos! for different types of a.”

You are talking about the function barrier example, where the problem is that the type is not known to the compiler (in fact, it is generated randomly).

However, in your code it should be known, if the compiler can figure it out from the caller of processData.

You are right @Tamas_Papp, the type of “data” my function caller is not random :wink:

You have misunderstood. This has nothing to do with what types you manually set on the function arguments. Julia will specialize the function on the argument types that occur during runtime.

Thanks @kristoffer.carlsson it is more clear with your explanation.

To word it in an other way, because I have seen people make the same mistake:

Argument type declarations in function signatures only serve to filter the input arguments. Having an AbstractString declaration will thus have your processData function accept only AbstractStrings and its subtypes. Trying to call processData with, for example, a number, will result in a method error.

1 Like

Thanks @jebej ! It is also said that “Declare types of keyword arguments will reduce the overhead of calls to the function” :slight_smile:

That’s for keyword arguments, and I believe that this overhead has been almost eliminated in 0.7. See #24987.

1 Like