Polymorphism: Difference between revisions

(→‎{{header|jq}}: def set_x)
Line 2,043:
</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:
<lang julia>
Circle(0;1;2) | print
</lang>
 
=={{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.
2,442

edits