Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use abstract type keyword in Julia?

What is the purpose of the 'abstract types' in Julia? Is there a use aside from using the type for the inheritance hierarchy?

abstract Animal

type Dog <: Animal
  sound
  color
end

type Bird <: Animal
  sound
  color
end

What is the purpose of this if it does not give the ability to inherit attributes and methods?

like image 689
Nicky Feller Avatar asked Mar 28 '16 17:03

Nicky Feller


2 Answers

Probably worth reading through the manual for this, as there are many uses for them.

Quoting from the manual one example:

Abstract types allow the construction of a hierarchy of types, providing a context into which concrete types can fit. This allows you, for example, to easily program to any type that is an integer, without restricting an algorithm to a specific type of integer.

like image 71
Daniel Arndt Avatar answered Sep 27 '22 19:09

Daniel Arndt


You say

if it does not give the ability to inherit attributes and methods?

But I disagree with that notion.

If you're thinking of abstract type as being like abstract classes in Java, that's probably tenuous at best. Start by thinking of them as interfaces. Let's say we wanted to have an interface Named for anything which has a reasonable concept of a name.

abstract type Named end
nameof(::Named) = ""

If you really wanted to, you could throw an exception in nameof if there's no reasonable default value.

Now, anybody can come along and subscribe to that interface.

struct Person <: Named
  name :: String
end
nameof(p::Person) = p.name

Now, let's say we want to say something about an entity, which may or may not have a name. We can use the name if it exists and fall back if not

message(entity, msg::String) = print(nameof(entity), " says ", msg)
message(entity::Named, msg::String) = print(nameof(entity), " says ", msg)

So you should think of abstract type as being like a Java interface but extensible, so we can "implement" the interface for existing types, such as built-in types and types we don't control. A type subscribes to the interface, which presumably defines a minimal set of functions, and then several other functions act on that interface, automatically extending to work on any type that's opted into the behavior.

like image 43
Silvio Mayolo Avatar answered Sep 27 '22 20:09

Silvio Mayolo