3 ms·
> The solution there is to add a method to the interface, and all your classes implement that. What if you don't know all methods that you will need in advance
by valenterry 3y ago
> The solution there is to add a method to the interface, and all your classes implement that.
What if you don't know all methods that you will need in advance?
That is the problem and this problem is solved by sealed classes. However, by doing so they introduce a new problem: what if you need more extending classes and you don't know all of them in advance? Which raises the question: is there a way to achieve both?
This problem is called expression problem. [1]
There are (statically typed) languages that are able to solve the expression problem, Java is one of them [2]. However, unfortunately the way to do that in Java is (still) very complex and unergonomic, hence rarely used. Languages like Haskell or, if you want to stay in the JVM world, Scala do much better here.
[1] https://en.wikipedia.org/wiki/Expression_problem https://en.wikipedia.org/wiki/Expression_problem
[2] https://koerbitz.me/posts/Solving-the-Expression-Problem-in-Haskell-and-Java.html https://koerbitz.me/posts/Solving-the-Expression-Problem-in-...