【问题标题】:Kotlin - Secondary constructor that differs by one argumentKotlin - 一个参数不同的辅助构造函数
【发布时间】:2017-03-12 06:45:00
【问题描述】:

我有一个 Kotlin 代码的 sn-p,其中第一个和第二个构造函数略有不同,见下文

class InstructionPrototype constructor(
      val iname: String,
      val opcode: Int,
      val mnemonicExample: String,
      val numericExample: Int,
      val description: String,
      val format: Format,
      val pattern: Pattern,
      var type: Type? = null,
      var rt: Int? = null,
      var funct: Int? = null,
      var conditions: Array<(n: Int) -> String?>? = null) {
  constructor(
        iname: String,
        opcode: Int,
        mnemonicExample: String,
        numericExample: Int,
        description: String,
        format: Format,
        pattern: Pattern,
        type: Type?,
        rt: Int?,
        funct: Int?,
        condition: (n: Int) -> String?
  ): this(iname, opcode, mnemonicExample, numericExample, description, 
        format, pattern, type, rt, funct, arrayOf(condition)) {

  }

是否可以通过某种语言结构来减少这种冗长?我在考虑代数数据类型,但感觉不太合适 - 它被认为是“hacky”。​​

【问题讨论】:

    标签: kotlin boilerplate verbosity


    【解决方案1】:

    Variable number of arguments (vararg) 似乎非常适合您的用例,但前提是您可以放弃将null 作为conditions 的默认值,因为vararg 不能为空(例如使用emptyArray()):

    class InstructionPrototype constructor(
          val iname: String,
          val opcode: Int,
          val mnemonicExample: String,
          val numericExample: Int,
          val description: String,
          val format: Format,
          val pattern: Pattern,
          var type: Type? = null,
          var rt: Int? = null,
          var funct: Int? = null,
          vararg var conditions: (n: Int) -> String? = emptyArray())
    

    在使用现场,可以传递单个(n: Int) -&gt; String?,它会被打包成一个数组,并且除了传递逗号分隔的几个函数外,还可以使用扩展运算符来传递一个数组:

    f(vararg a: String) { }
    
    f("a")
    f("a", "b", "c")
    
    val array = arrayOf("a", "b", "c")
    f(*array) // any array of the correct type can be passed as vararg
    

    另外,conditions 之前的几个参数也有默认值,除了使用named arguments 和扩展运算符之外,没有其他方法可以跳过它们并传递conditions

    fun f(x: Int = 5, vararg s: String) { }
    
    f(5, "a", "b", "c") // correct
    f(s = "a") // correct
    f(s = "a", "b", "c") // error
    f(s = *arrayOf("a", "b", "c") // correct
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多