【问题标题】:Structural typing in Scala: use abstract type in refinementScala中的结构类型:在细化中使用抽象类型
【发布时间】:2014-05-22 10:42:39
【问题描述】:

假设我有以下代码:

class Bar { def bar(b:Bar):Boolean = true }
def func(b:Bar) = b.bar(b)    

以上工作正常。 Bar 类是在第三方库中定义的,有几个类似的类,每个类都有一个bar 方法,例如

class Foo { def bar(f:Foo):Boolean = false }

我不想为每个此类编写func,而是想使用泛型类型B 定义func,只要它具有正确签名的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 的代码的情况下做我想做的事吗?

【问题讨论】:

    标签: scala structural-typing


    【解决方案1】:

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

    我建议使用解决方法。方法定义的函数式方法,因为 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) 
    

    优缺点 函数类型 VS 方法类型定义here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多