Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run code before calling the primary constructor?

Tags:

kotlin

I am writing a class that contains two immutable values, which are set in the primary constructor. I would like to add a secondary constructor that takes a string and parses it to get those two values. However, I can't figure out a way to implement this in Kotlin, as the secondary constructor calls the primary constructor immediately, before parsing the string.

In java, I would call this(a,b) in one of the other constructors, but Java doesn't have primary constructors. How do I add this functionality?

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
  }
}
like image 983
BillThePlatypus Avatar asked Jun 14 '26 16:06

BillThePlatypus


1 Answers

You can either replace your parsing constructor with a factory method:

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)
        }
    }
}

Or make both constructors secondary:

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
    }
}
like image 110
Bananon Avatar answered Jun 18 '26 01:06

Bananon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!