构造函数中的默认值显示Kotlin中的错误

时间:2018-11-27 11:59:21

标签: android mvvm kotlin

我的操作与herehere中的操作相同,但显示错误

这是我的课程,其课程primary constructor没有secondary constructor没有init块。

class RowSubTShirtViewModel(private val subTShirtAdapter: SubTShirtAdapter, val context: TShirtActivity,
                            val tShirtBean: CommonItemBean, private val parentPosition: Int, private val position: Int) : BaseObservable(), TShirtActivity.setSelectionSubRow {}

创建类似val vm=RowSubTShirtViewModel()的对象并给出错误

  
      
  • 创建抽象函数'RowSubTShirtViewModel'
  •   
  • 创建函数“ RowSubTShirtViewModel”
  •   
  • 创建辅助构造函数
  •   
  • 没有传递参数值
  •   

2 个答案:

答案 0 :(得分:1)

您需要将参数显式传递给主构造函数:

//init params
val subTShirtAdapter = ...
val context = ...
val tShirtBean = ...
val parentPosition = ...
val position = ...

//init viewModel
val vm = RowSubTShirtViewModel(subTShirtAdapter, context, tShirtBean, parentPosition, position)

除非您为参数分配默认值,例如:

class RowSubTShirtViewModel(private val subTShirtAdapter = YourAdapter(),...)

根据您的情况,您可以执行以下操作:

class RowSubTShirtViewModel(val context: TShirtActivity, 
    private val subTShirtAdapter: SubTShirtAdapter, 
    val tShirtBean: CommonItemBean, 
    private val parentPosition: Int = 0, 
    private val position: Int = 0) : BaseObservable(), TShirtActivity.setSelectionSubRow {}

// and then create an instance
val vm = RowSubTShirtViewModel(yourContext, yourAdapter, yourShirtBean)

答案 1 :(得分:0)

您没有在构造函数中使用default arguments。如果您想使用,它应该看起来像

class RowSubTShirtViewModel(
    private val subTShirtAdapter: SubTShirtAdapter = defaultSubTShirtAdapter,
    val context: TShirtActivity = defultContext,
    val tShirtBean: CommonItemBean = defaultTShirtBean,
    private val parentPosition: Int = defaultParentPosition,
    private val position: Int = defaultPosition) : BaseObservable(), TShirtActivity.setSelectionSubRow {}