代码之家  ›  专栏  ›  技术社区  ›  Farhana Naaz Ansari Debashish Dwivedi

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

  •  0
  • Farhana Naaz Ansari Debashish Dwivedi  · 技术社区  · 6 年前

    我也这么做 here here 但显示出错误

    这是我的班级 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 回复  |  直到 6 年前
        1
  •  1
  •   Sergio    6 年前

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

    //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)
    
        2
  •  0
  •   Feedforward    6 年前

    你没有使用 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 {}