Scala 隐式参数的默认行为

Scala 隐式参数的默认行为,scala,implicit,Scala,Implicit,是否可以为类的隐式参数表示默认值 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) } 上面的代码给出了“error:notfound:val

是否可以为类的隐式参数表示默认值

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)
}

上面的代码给出了“error:notfound:value key”

您不能在构造函数中引用类的成员,因为该类尚未构造。i、 e.
key
a
的成员,因此不能在类构造函数中引用
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 = A@29ba4338
或者,如果您想让它更干净一点,可以在
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
}

您不能在构造函数中引用类的成员,因为该类尚未构造。i、 e.
key
a
的成员,因此不能在类构造函数中引用
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 = A@29ba4338
或者,如果您想让它更干净一点,可以在
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
}

您不能在构造函数中引用类的成员,因为该类尚未构造。i、 e.
key
a
的成员,因此不能在类构造函数中引用
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 = A@29ba4338
或者,如果您想让它更干净一点,可以在
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
}

您不能在构造函数中引用类的成员,因为该类尚未构造。i、 e.
key
a
的成员,因此不能在类构造函数中引用
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 = A@29ba4338
或者,如果您想让它更干净一点,可以在
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
}

使用这种方法很明显,但实际情况更为复杂,我有多个构造函数,是否可以最小化代码副本。@kokorins您也可以将函数放在类的伴生对象中。这可以使它更干净。使用这种方法很明显,但实际情况更复杂,我有多个构造函数,是否可以最小化代码副本。@kokorins您也可以将函数放在类的伴生对象中。这可以使它更干净。使用这种方法很明显,但实际情况更复杂,我有多个构造函数,是否可以最小化代码副本。@kokorins您也可以将函数放在类的伴生对象中。这可以使它更干净。使用这种方法很明显,但实际情况更复杂,我有多个构造函数,是否可以最小化代码副本。@kokorins您也可以将函数放在类的伴生对象中。这样可以保持清洁。