2016-10-04 12 views
0

我试图使用函数使用混入组合物,但是我有在obj对象的apply方法的错误:使用混入组合物与在阶函数

重写方法适用于(s: String)String类型的trait t;方法apply需要abstract override修饰符。

如何解决这个错误,哪个是正确的implement法?

trait t extends Function1[String,String] { 
    abstract override def apply(s: String): String = { 
    super.apply(s) 
    println("Advice" + s) 
    s 
    } 
} 

object MixinComp { 
    def main(args: Array[String]) { 
    val obj = new Function1[String, String] with t { 
     override def apply(s: String) = s 
    } 
    println(obj.apply("Hi")) 
    } 
} 

回答

0

你不会需要使用abstract修改您的t特征定义,如果你不叫super.apply。在这种特殊情况下,我没有看到调用super.apply的任何需要,因为Function1的应用是抽象的。您可能需要自定义应用实现。下面的代码应该可以工作。

trait t extends Function1[String, String] { 
    override def apply(s: String): String = { 
    // super.apply(s) 
    println("Advice" + s) 
    s 
    } 
} 

案例1:使用重写应用方法t特点:

val obj = new Function1[String, String] with t {} 
obj.apply("hello") // prints: Advicehello 

案例2:覆盖t特质的应用方法的匿名类:

val obj = new Function1[String, String] with t { 
    override def apply(s: String): String = s 
} 

obj.apply("hello") // prints hello 
+0

这不回答这个问题 – Dima

1

立即解决问题(它抱怨错误的原因)是,您不能在线性化流程中进行抽象调用(您的t.apply调用super.apply,这是抽象的)。

此外,您在顶级匿名类中定义的apply方法会覆盖所有内容,并且不会调用super,使得t被完全不相关地混合在一起。

像这样的事情会解决这两个问题:

trait t extends Function1[String,String] { 
    abstract override def apply(s: String): String = { 
    println("Advice" + s) 
    super.apply(s) // I rearranged this a little, because it kinda makes more sense this wat 
    } 
} 

// Note, this extends `Function1`, not `t`, it, just a "vanilla" Function1 
class foo extends Function1[String, String] { 
    def apply(s: String): String = s 
} 


// Now I am mixing in the t. Note, that the apply definition 
// from foo is now at the bottom of the hierarchy, so that 
// t.apply overrides it and calls it with super 
val obj = new foo with t 
obj("foo")