Home > Mobile >  Kotlin - accessing and using constructor parameters
Kotlin - accessing and using constructor parameters

Time:01-28

I have this constructor in a class inside my interface (it's supposed to be more like a static structure but for now this is ok)

class BinData {
        constructor(card_id: Int,
                    from: Int,
                    to: Int)
    }

I created an instance, and I want to use all properties inside constructor in a form of a map as an argument for function

val binData = IConfiguration.BinData(2, 222100, 272099)
memoryConfig.binAdd(1, binData)

Of course then, when I printed the line in binAdd() I got Bin added: {1=control.app.activities.IConfiguration$BinData@8bd0008} which is just object hash

What is the reasonable way to approach this? I thought of a creating a method like BinData.getdata() which would return Map of parameters but I'm really not sure that's the way.

For any help I'll be glad. Thanks.

CodePudding user response:

Constructor parameters can only be properties if they are in the primary constructor, declared before the { }. And toString() will only list the property values if your class is a data class or if you override toString() to manually define this behavior.

You should declare your class like this:

data class BinData(
    val card_id: Int,
    val from: Int,
    val to: Int
)

CodePudding user response:

You're just declaring a constructor that receives 3 parameters but you're not specifying that those are properties. I'd recommend you setting a primary constructor with those properties

class BinData(val card_id: Int,
              val from: Int,
              val to: Int)

Notice that I specified those properties as val assuming that they're immutable. If you need to modify them, make them mutable by defining them as var

Consider also using a data class if your class is meant to only hold values and not logic

  •  Tags:  
  • Related