2015-06-08 39 views
0

是否可以爲類的隱式參數表示默認值?上述隱式參數的默認行爲

class I[T](val t: T) 

class A(i: I[Int])(implicit f: I[Int] => Int) { 

    implicit object key extends(I[Int] => Int) { 
     def apply(i: I[Int])= i.t 
    } 

    def this() = this(new I(0))(key) 
} 

的代碼提供「錯誤:未找到:值鍵」

回答

3

你不能指在構造函數中的一類的成員,因爲類尚未建立呢。即keyA的成員,所以你不能在類構造函數中引用key。然而,你可以使用默認的參數作爲一個匿名函數:

scala> class A(i: I[Int])(implicit f: I[Int] => Int = { i: I[Int] => i.t }) 
defined class A 

scala> new A(new I(2)) 
res1: A = [email protected] 

或者,如果你想讓它多一點乾淨的,你可以在A同伴對象創建一個方法,並引用它。

case class A(i: I[Int])(implicit f: I[Int] => Int = A.key) 

object A { 
    def key(i: I[Int]): Int = i.t 
} 

甚至:

case class A(i: I[Int])(implicit f: I[Int] => Int) { 
    def this() = this(new I(0))(A.key) 
} 

object A { 
    def key(i: I[Int]): Int = i.t 
} 
+0

很明顯,使用此方法,但實際的情況是更comlicated,我有多個構造函數,是可以減少代碼的副本。 – kokorins

+0

@kokorins您也可以將該函數放入該類的伴隨對象中。這可以保持清潔。 –