假设我有以下代码:
class Bar { def bar(b:Bar):Boolean = true }
def func(b:Bar) = b.bar(b)
以上工作正常。该类Bar
是在第 3 方库中定义的,并且有几个类似的类,每个类都有一个bar
方法,例如
class Foo { def bar(f:Foo):Boolean = false }
func
我不想为每个此类编写,而是想func
使用泛型类型进行定义B
,只要它具有bar
正确签名的方法即可。
我尝试了以下方法,但它给了我一个错误:
def func[B <: {def bar(a:B):Boolean}](b:B) = b.bar(b) // gives error
我得到的错误是:
<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)
^
但是,如果我执行以下操作,则方法定义有效,但调用会出错:
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)
^
有什么方法可以在不更改代码的情况下做我想做的事Bar
吗?