Kotlin抽象类二级构造函数

时间:2019-01-08 08:09:27

标签: android kotlin

我无法为此抽象类创建辅助构造函数。

@SuppressLint("StaticFieldLeak")
abstract class BaseAndroidViewModel(
        application: Application,
        private val creditsGetByIdUseCase: CreditsGetByIdUseCase,
        private val videosGetByIdUseCase: VideosGetByIdUseCase,
        private val reviewGetByIdUseCase: ReviewGetByIdUseCase,
        private val addToFavoritesUseCase: AddToFavoritesUseCase,
        private val getFavoriteByIdUseCase: GetFavoriteByIdUseCase
) : AndroidViewModel(application) {

constructor(application: Application) : this(application) // There's a cycle in the delegation calls chain error

3 个答案:

答案 0 :(得分:4)

您可以像这样调用辅助构造函数-

@SuppressLint("StaticFieldLeak") abstract class BaseAndroidViewModel : AndroidViewModel{
constructor(application: Application,
            creditsGetByIdUseCase: CreditsGetByIdUseCase,
            videosGetByIdUseCase: VideosGetByIdUseCase,
            reviewGetByIdUseCase: ReviewGetByIdUseCase,
            addToFavoritesUseCase: AddToFavoritesUseCase,
            getFavoriteByIdUseCase: GetFavoriteByIdUseCase) : super(application)

constructor(application: Application) : super(application) }

答案 1 :(得分:2)

在创建 secondary 构造函数时,如果一个类具有非空的 primary 构造函数,则应传递 primary 构造函数具有的所有参数,例如:

<PKT>
   <Method Name="GetBalance">
      <Auth Login="" Password="" />
      <Params>
         <Param1 Type="string" Value="AAD8EE30-8C43-11DC-9755-668156D89593" /> 
         <Param2 Type="string" Value="AAD8EE30-8C43-11DC-9755-668156D89593" />
      </Params>
   </Method>
</PKT>

在您的情况下,可能是以下情况:

/* Redefine macro to redirect scanner input from string instead of
 * standard input.  */
#define YY_INPUT( buffer, result, max_size ) \
{ result = input_from_string (buffer, max_size); }

或者您可以使用默认参数创建主要构造函数:

abstract class BaseAndroidViewModel(
        application: Application,
        private val creditsGetByIdUseCase: String,
        private val videosGetByIdUseCase: String
) : AndroidViewModel(application) {

    constructor(application: Application) : this(application, 
            "creditsGetByIdUseCase", "videosGetByIdUseCase") // here we pass other necessary parameters
}

答案 2 :(得分:0)

获得cycle in the delegation calls chain error的原因是因为

constructor(application: Application): this(application)

等效于java:

public MyClass(Application application){
    this(application)
}

这表示您正在递归地调用构造函数。


Alok Mishra's answer中所述,您应该改为调用超级构造函数。

constructor(application: Application): super(application)

这实际上等效于您的主要构造函数:

BaseAndroidViewModel(application: Application): AndroidViewModel(application)

您可以确定这只是将constructor的关键字BaseAndroidViewModel替换为super的关键字AndroidViewModel