3 ms·
Classes in C++ and Python are essentially types bundled with a bunch of methods associated with that type. In a multiple dispatch [1] language like Julia, metho
by StefanKarpinski 8y ago
Classes in C++ and Python are essentially types bundled with a bunch of methods associated with that type. In a multiple dispatch [1] language like Julia, methods are not associated only with the first argument—they "belong to" all of the arguments. This is because which method is called depends on the types of all of the arguments, not just the first one, so it no longer makes sense to associate those methods only with the type of the first argument. Therefore it also no longer makes sense for method definitions to live "inside of" the type—aka "class"—of the first argument. Therefore, you don't have classes as bundles of types with their methods anymore—because the methods don't belong to the types. Instead, they belong to "generic function" objects, which are a first class abstraction for what in a class-based language is just a collection of methods that happen to have the same name (and may or may not actually be conceptually related). In short, you could shoehorn something that looks like a class into Julia, but it wouldn’t really make any sense.
To answer the next-level question of "why multiple dispatch?"... Multiple dispatch is a generalization of single dispatch and leads to much more composable, extensible systems, largely by providing a simple, intuitive and efficient solution to the somewhat esoteric-sounding “Expression Problem” [2]. Even though the problem sounds obscure, it has profound practical consequences and most of the stumbling blocks to writing reusable, composable code in both object oriented and functional languages boil down to it being hard to either extend existing operations to new types or to define new operations on existing types. Julia does both so easily that it’s easy to forget that it’s a problem in other languages. Multiple dispatch is also a particularly good fit for numerical programming problems where it often makes little sense for a specialized operation to "belong" only to its first argument. For example, `x + y` doesn't belong to `x` any more than it does to `y`.
[1] https://en.wikipedia.org/wiki/Multiple_dispatch https://en.wikipedia.org/wiki/Multiple_dispatch
[2] https://en.wikipedia.org/wiki/Expression_problem https://en.wikipedia.org/wiki/Expression_problem