kokorins
kokorins

Reputation: 72

Default behaviour for implicit arguments

Is it possible to express a default value for the implicit argument for a class?

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

the code above gives "error: not found: value key"

Upvotes: 0

Views: 51

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

You cannot refer to members of a class within the constructor, because the class hasn't been constructed yet. i.e. key is a member of A, so you cannot refer to key within the class constructor. You can however use a default parameter as an anonymous function:

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

Or, if you want to make it a little more clean, you can create a method in the companion object of A, and reference it.

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

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

Or even:

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
}

Upvotes: 3

Related Questions