To illustrate my point, here is an example:
abstract class Wrapper[A](wrapped: A) { protected def someCondition: Boolean def fold[B](whenTrue: => B)(whenFalse: => B): B = if (someCondition) whenTrue else whenFalse }
I am trying to add a fold method based on an arbitrary condition defined on wrapped type A The problem with the above code is that this did not compile, although it is possible to possibly return Any :
wrapper.fold("hi")(42)
because by the time the compiler reaches the second parameter list, B has already been output as String . Suppose we do not want to write a type annotation. We can try changing fold to this:
def fold[B, B0 >: B](whenTrue: => B)(whenFalse: => B0): B0
but this also does not work, since B0 already resolved as a String at the end of the first parameter list, although it does not appear at all in it! A simple solution, of course, is to have a single list of parameters, but, for the sake of example, let's say I want to save two lists of parameters and try to make it work ... Ideally, we should be able to delay the resolution of B0 . It would be great if we could write something like this:
def fold[B](whenTrue: => B)[B0 >: B](whenFalse: => B0): B0
But, unfortunately, this does not work. Are there any workarounds?
(I give the first answer, but of course I am looking for other workarounds).
source share