Search code examples
scalaimplicit

Multiple constructor and implicit parameter


I have some scala code

class A (a: Int, b:Int) (implicit typeinfo: TypeInformation[T]) {
  ...
}

but if i define a new constructor

class A (a: Int, b:Int) (implicit typeinfo: TypeInformation[T]) {
  def this(a: Int]) {
      this(a, 0)   
  }
  ...
}

the compiler throws "could not find implicit value for parameter" error. I tried this(a,0)(typeinfo) but got the same error

What could be the cause?


Solution

  • The main constructor is the one when you defined at the class declaration

    this is a secondary constructor and it's still a function, you need to define the implicit in the declaration.

    if you do this:

    class A (a: Int, b:Int) (implicit typeinfo: TypeInformation[T]) {
      def this(a: Int])(implicit typeinfo: TypeInformation[T]) {
          this(a, 0)   
      }
      ...
    }
    

    It will work.