I don’t fully grasp when you would use parametric types or abstract types in methods.
Before posting my question, I did attempt to read and try and answer the question for myself.
Consider the following code:
abstract type Character end
abstract type Alien <: Character end
struct Gray <: Alien
name::String
age::Int32
favourite_food::String
end
struct BlueAlien <: Alien
name::String
favourite_song::String
end
struct Human <: Character
name::String
end
Consider the following function that uses the where
keyword:
function share_food(character_that_has_food::A,
character_that_receives_food::A,
food::String) where {A <: Character}
println("Working with $(typeof(character_that_has_food)) and
$(typeof(character_that_receives_food))")
println("Sharing a $(food) with my friend
$(character_that_receives_food.name)")
end
mort = Gray("Mort",1000,"Fries")
zorotl = BlueAlien("Zorotl","Blue - Eiffel 65")
share_food(mort,zorotl,"Cheese Burger and Apple Pie")
I don’t see any distinction between the above function and this function:
function share_food(character_that_has_food::Character,
character_that_receives_food::Character,
food::String)
println("Working with $(typeof(character_that_has_food)) and
$(typeof(character_that_receives_food)).")
println("Sharing a $(food) with my friend
$(character_that_receives_food.name).")
end
Both do the same thing but in a different ways. The first share_food()
example uses A
as the variable, and I can use that variable just like any other variable.
- What situation would you use that variable containing the type? The only situation that I can think of is when you want to do something with a type, but don’t care about the type.
For example, create a collection of aliens generate_alien_vector(aliens_from_db::A) where A <: Alien
. Now I don’t care what alien I pass in to generate the vector.
The problem is, with just abstract types I can do the same thing, because Julia knows the specific type it’s given. For example, calling the above share_food()
function without the where
:
Working with Gray and BlueAlien.
Sharing a Cheese Burger and Apple Pie with my friend Zorotl.
I can even capture the result of typeof()
and use it to create a collection.
The example shown in the above link uses generics to allow any type of IBusinessObject
but still be able to retrieve the concrete type to call the properties specifc to that type.
- Can you carry out a task with parametric functions that you can’t with functions that accept only abstract types?