首页 > 解决方案 > 多个构造函数和隐式参数

问题描述

我有一些scala代码

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

但是如果我定义一个新的构造函数

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

编译器抛出“找不到参数的隐式值”错误。我试过this(a,0)(typeinfo)但得到了同样的错误

可能是什么原因?

标签: scalaimplicit

解决方案


主构造函数是您在类声明中定义的构造函数

this是一个辅助构造函数,它仍然是一个函数,你需要在声明中定义隐式。

如果你这样做:

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

它会起作用的。


推荐阅读