Let's say I have the following code:
class Bar { def bar(b:Bar):Boolean = true } def func(b:Bar) = b.bar(b)
The above works fine. The Bar class is defined in a third-party library, and there are several similar classes, each of which has a Bar method, for example
class Foo { def bar(f:Foo):Boolean = false }
Instead of writing func for each such class, I want to define func using the generic type B , since it has the Bar method of the correct signature.
I tried the following, but this gives me an error:
def func[B <: {def bar(a:B):Boolean}](b:B) = b.bar(b) // gives error
The error I get is:
<console>:16: error: Parameter type in structural refinement may not refer to an abstract type defined outside that refinement def func[B <: {def bar(a:B):Boolean}](b:B) = b.bar(b) ^
However, if I do the following, the method definition works, but the call causes an error:
def func[B <: {def bar(a:Any):Boolean}](b:B) = b.bar(b) func(new Bar) <console>:10: error: type mismatch; found : Bar required: B func(new Bar) ^
Is there a way to do what I want without changing the Bar code?
scala structural-typing
Jus12
source share