Polymorphism: Difference between revisions

Content added Content deleted
(→‎{{header|jq}}: def set_x)
Line 2,043: Line 2,043:
</lang>
</lang>


In practice, it's unlikely one would want to write accessors, as .x will retrieve "x", etc; similar remarks apply to setters (.x = VALUE). `.` will copy, and empty could serve as a destructor, in that `Point(0) | empty` produces the empty stream.

For the sake of illustration, though, one could define a type-checking "set_x" as follows:

<lang jq>
def set_x(x):
if type == "Point" or type == "Circle" then .x = x
else error("set_x: invalid type: \(.)")
end;
</lang>
Example:
Example:
<lang julia>
<lang julia>
Circle(0;1;2) | print
Circle(0;1;2) | print
</lang>
</lang>

=={{header|Julia}}==
=={{header|Julia}}==
There is no obvious inheritance hierarchy here to get polymorphism. Julia has multiple dispatch, so the appropriate implementation of the print function will be called at runtime depending on the type of the arguments provided. The import of Base.print is done to allow the print function to dispatch on some new types you define.
There is no obvious inheritance hierarchy here to get polymorphism. Julia has multiple dispatch, so the appropriate implementation of the print function will be called at runtime depending on the type of the arguments provided. The import of Base.print is done to allow the print function to dispatch on some new types you define.