【问题标题】:Default value in Constructor showing error in Kotlin构造函数中的默认值在 Kotlin 中显示错误
【发布时间】:2018-11-27 11:59:21
【问题描述】:

我的操作与 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”
  • 创建二级构造函数
  • 没有为参数传递值

【问题讨论】:

标签: android mvvm kotlin


【解决方案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)

【讨论】:

  • 我完全按照教程和答案所说的那样做。你能解释一下我哪里做错了吗?
  • 您刚刚错过了分配默认参数,请参阅我编辑的答案。
  • 如果我按顺序排列参数,并且上下文将是第一个那么就可以了。
  • 但在您的情况下,我认为没有理由使用默认参数创建 RowSubTShirtViewModel,因为它们应该在顶层初始化(创建 RowSubTShirtViewModel 的实例)
  • 顶层是什么意思?
【解决方案2】:

您没有在构造函数中使用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 {}

【讨论】:

  • 如果我按顺序排列参数,并且上下文将是第一个那么就可以了。
  • 我为该类创建了默认参数函数,显示没有编译时错误,但在运行时显示 KNP。我的目标是从活动中调用接口方法,并且该类已经实现了接口。
猜你喜欢
  • 2018-04-23
  • 1970-01-01
  • 2017-04-08
  • 2021-06-06
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多