ausgeorge
ausgeorge

Reputation: 1015

Secondary Constructor param

Can someone please help me work this out? My object had 3 main parameters, all Strings. I now want to add a secondary constructor with an single emum parameter, which in turn would set each of the 3 original params, as follows;

class MyObject(var string1: String, var string2: String, var string3: String)
{
    constructor(presetCode: PresetCode ) : this("", "", "")
    {
      when (presetCode)
      {
       PresetCode.Code1 ->
        {
         string1 = "aaa"
         string2 = "bbb"
         string3 = "ccc"
        }
       }
      }

   var anotherObject = AnotherObject(string1)

}

The issue is AnotherObject(string1) isn't working, as string1 is just an empty string.

how can I set the 3 params using this secondary constructor and then successfully call AnotherObject(string1)? thanks

Upvotes: 0

Views: 72

Answers (2)

gidds
gidds

Reputation: 18617

One option is to replace the secondary constructor with an invoke() method on the companion object:

class MyObject(var string1: String, var string2: String, var string3: String) {
    companion object {
        operator fun invoke(presetCode: PresetCode) = when (presetCode) {
            PresetCode.Code1 -> MyObject("aaa", "bbb", "ccc")
            else -> MyObject("", "", "")
        }
    }

    var anotherObject = AnotherObject(string1)
}

In use, it looks just like a constructor call, e.g.:

val o = MyObject(PresetCode.Code1)

This approach is simple, concise, and very flexible.  (For example, it could return a cached instance instead of creating a new one.)

Upvotes: 2

chronoxor
chronoxor

Reputation: 3559

Here is a solution I found based on your class design which requires single AnotherObject construction per MyObject instance:

class MyObject
{
    constructor(s1: String, s2: String, s3: String)
    {
        string1 = s1
        string2 = s2
        string3 = s3
        anotherObject = AnotherObject(string1)
    }

    constructor(presetCode: PresetCode)
    {
        when (presetCode)
        {
            PresetCode.Code1 ->
            {
                string1 = "aaa"
                string2 = "bbb"
                string3 = "ccc"
            }
            else ->
            {
                string1 = ""
                string2 = ""
                string3 = ""
            }
        }
        anotherObject = AnotherObject(string1)
    }

    var string1: String
    var string2: String
    var string3: String
    var anotherObject: AnotherObject
}

Hope this helps.

Upvotes: 1

Related Questions