如何在调用主构造函数之前运行代码?

Bil*_*pus 5 kotlin

我正在编写一个包含两个不可变值的类,它们在主构造函数中设置。我想添加一个辅助构造函数,它接受一个字符串并解析它以获取这两个值。但是,我无法找到在 Kotlin 中实现此功能的方法,因为辅助构造函数在解析字符串之前立即调用主构造函数。

在 java 中,我会调用this(a,b)其他构造函数之一,但 Java 没有主构造函数。如何添加此功能?

class Object (a: double, b:double)
{
  val a = a
  val b = b
  constructor(str: String) //Parsing constructor
  {
    //Do parsing
    a = parsed_a
    b = parsed_b
  }
}
Run Code Online (Sandbox Code Playgroud)

Ban*_*non 9

您可以用工厂方法替换解析构造函数:

class Object(val a: Double, val b: Double) {
    companion object {
        // this method invocation looks like constructor invocation
        operator fun invoke(str: String): Object {
            // do parsing
            return Object(parsed_a, parsed_b)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

或者将两个构造函数设为次要:

class Object {
    val a: Double
    val b: Double

    constructor(a: Double, b: Double) {
        this.a = a
        this.b = b
    }

    // parsing constructor
    constructor(str: String) {
        // do parsing
        a = parsed_a
        b = parsed_b
    }
}
Run Code Online (Sandbox Code Playgroud)


use*_*450 4

Kotlin 不喜欢辅助构造函数。最好的解决方案是使用工厂方法。参见,例如:

class A(val a: Int, val b: Int) {
    companion object {
        fun fromString(str: String): A {
            val (foo, bar) = Pair(1, 2) // sub with your parsing stuff
            return A(foo, bar)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这将导致代码更具可读性。想象一下,一个具有十个不同构造函数的类除了MyClass通过工厂方法启用许多更明显的构造函数之外别无其他方式:MyClass.fromString(str: String)等等MyClass.fromCoordinates(coordinates: Pair<Int, Int>)

直到最近,Kotlin 中才允许使用辅助构造函数。