Coercing into a type

Sorry but I don’t know a better term than coercing.

Suppose that I read a set of strings and some times all of those strings can all be converted to InlineStrings.String15, which I prefer for performance, and some times not.

What is the cleanest way to do this?

Here’s one that I can think of, but I don’t like because I hate exceptions:

s1 = ["kdjhfgksjdhfgkljsdhf", "lkjsdflskdflskdjflkfljs", "ldkfglkdfjglkdjfglkd"]
s2 = ["dfg", "dfg", "hkfj"]

maybeconvert(ss) = try
    InlineStrings.String15.(ss)
catch
    ss
end

maybeconvert(s1)  # Vector{String}
maybeconvert(s2)  # Vector{String15}


String15 can store up to 15 codeunits. So you can check if ncodeunits of each string is 15 or fewer:

function maybe_convert_string15(v::AbstractVector{<:Union{String, SubString{String}}}
    all(s -> ncodeunits(s) < 16, v) ? InlineStrings.String15.(v) : v
end

Your method also works, but checking the codeunits is more explicit about which error case you check for (i.e. you don’t accidentally catch some other exception).