How (or whether) to force correct handling of different return types?

I have a stylistic question. From statically compiled languages I am used to having to define what a function’s return values can be. In Julia, I don’t have to. Let’s take circle line intersection as an example. The result can be 1. no intersection, 2. one intersection (tangent) or 3. two intersections. How do I force the code using the result from this function to deal with the different return types? Ideally, I would want to have an instantiation of a union type, like Union{nothing, Line, Tuple{Line, Line}} but that is not a leaf type. What are some patterns that are useful in this case? Creating a special return type?

1 Like

An array of intersections seems to be reasonable in this case?

Yes, it would allow more than 2 intersections which is impossible for this use case. If you want to deal with that then you can use @assert as a post-condition before returning the data, or for more control just create a custom struct to store the return data.

1 Like

Ideally you never have to manipulate or calculate types at all directly. This is generally not feasible for complex code, but should be the ideal you strive for. Eg

intersections = calculate_intersection.(circles, lines)

should “just work”, creating an object of the correct type. To deal with the elements, just use multiple dispatch. When the number of types is small, the compiler can handle it OK. See

1 Like