Giuseppe
Giuseppe

Reputation: 550

Edit class constructor's variables before instantiate the parent

I would like to change the constructor variable before initializing the parent class. It's a "final" variable so I have no way to initialize it later.
I'm a recent user of Kotlin and don't know how to do this, the idea would be something like this:

class JsonMessage : OutboundMessage {
    constructor(exchange: String, routingKey: String, body: ByteArray) {
        val basicProperties = BasicProperties.Builder().build()
        super(exchange, routingKey, basicProperties, body)
    }
}

Upvotes: 1

Views: 625

Answers (1)

Joffrey
Joffrey

Reputation: 37680

Since this only affects one argument, you can inline the variable and use the following syntax:

class JsonMessage : OutboundMessage {
    constructor(exchange: String, routingKey: String, body: ByteArray) : super(exchange, routingKey, BasicProperties.Builder().build(), body)
}

If the initialization expression is longer, you can extract it into a function.

If you need some more complex computation that defines multiple constructor arguments, you can instead define a factory function that looks like a constructor:

fun JsonMessage(exchange: String, routingKey: String, body: ByteArray) {
    // whatever you want here
    val basicProperties = BasicProperties.Builder().build()
    val (other1, other2) = someComplexStuffReturningMultipleValues()

    return JsonMessage(exchange, routingKey, basicProperties, other1, other2, body)
}

Side note: since you mention you're new to Kotlin, you may not have seen the distinction between primary constructors and secondary constructor syntax. You're using a secondary constructor syntax here, but you can also declare this constructor right in the class declaration:

class JsonMessage(exchange: String, routingKey: String, body: ByteArray) : OutboundMessage(exchange, routingKey, BasicProperties.Builder().build(), body) {
    // .. class body here
}

And then have a constructor that maps one-to-one to the parent.

Upvotes: 2

Related Questions