2016-10-04 11 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")