Scala中的结构类型:在细化中使用抽象类型

Jus*_*s12 7 scala structural-typing

说我有以下代码:

class Bar { def bar(b:Bar):Boolean = true }
def func(b:Bar) = b.bar(b)    
Run Code Online (Sandbox Code Playgroud)

以上工作正常.该类Bar在第三方库中定义,并且有几个类似的类,每个类都有一个bar方法

class Foo { def bar(f:Foo):Boolean = false }
Run Code Online (Sandbox Code Playgroud)

func我想要定义func使用泛型类型B ,而不是为每个这样的类编写,只要它有一个bar正确签名的方法.

我尝试了以下但它给了我一个错误:

def func[B <: {def bar(a:B):Boolean}](b:B) = b.bar(b) // gives error
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

<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)
                       ^
Run Code Online (Sandbox Code Playgroud)

但是,如果我执行以下操作,方法定义仍然有效,但调用会产生错误:

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)
               ^
Run Code Online (Sandbox Code Playgroud)

有没有办法在不改变代码的情况下做我想做的事情Bar

Yur*_*riy 2

在方法参数的结构类型之外定义抽象类型的问题就足够了。其次,您的方法不起作用,因为方法签名不相等(看起来像方法重载)。

我建议使用解决方法。方法定义的函数式方法,因为 Function1[-T1, +R] 是已知类型:

class Bar { def bar : Bar => Boolean = _ => true }
class Foo { def bar : Foo => Boolean = _ => false }

def func[T <: { def bar : T => Boolean } ](b: T): Boolean = b.bar(b)

func(new Bar)
func(new Foo) 
Run Code Online (Sandbox Code Playgroud)

缺点和优点函数类型VS方法类型定义在这里