2015-06-08 35 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您也可以将该函数放入该类的伴随对象中。这可以保持清洁。 –