I just asked this question about Rust: Is it possible to create a default trait implementation in Rust, and then override that trait implementation somewhere else? My problem is, in my custom lang, I want to define a default implementation for printing error messages to the terminal. What I hate the most about JS/Node.js is the error message printing is terrible, so I would like to override all error messages and reformat it. Likewise in my language, I wanted to have the ability to override how error messages are displayed. And other things will use this pattern, but this is just top-of-mind.
The question is, how can I:
- Define the default implementation of stringifying?
- Allow overriding (possibly multiple times) of the stringification?
By multiple times, I mean a library might define some errors and renderings for them. Then another library might override that. Then an application might override that, so 3 layers of definitions, the last one which will take precedence (and all internal/external error messages will use that final formatter).
How can I do this in a statically typed sort of way? It appears Rust doesn't allow you to override trait implementations (for some reason I'm unaware of, waiting to hear about that!). Could you theoretically just add that feature to Rust without consequences? What about other languages, what is a good example how another language solves this problem?
In some ways it's kind of like dependency injection, but not 100% sure about that.
alias_method
in Ruby? Could that be done in a statically typed sort of language somehow? $\endgroup$given
as one answer already mentions, which are more exactly like the "overridden trait implementation" solution you describe, but it also hasimplicit
variables, which allow actual dependency injection too. I guess these both solve the same problem in parallel ways? I don't know enough about Scala to answer for sure though. $\endgroup$