kotlinprimary-constructor

How do I pass data from a variable into a constructor using the body of the variable?


I am trying to assign data to my class using the variable that I created. I want to use the variable as an instance of the membership class. Every time I pass any values I get an error.

error: no value passed for parameter '_number'

var member1 = membership()

error: unresolved reference: _number

member1._number = 1

I am getting this for all properties I try to pass anything to.

I tried to create the class without any constructors but I would still get errors. My goal is to create a list of the variables.

class membership(_number:Int, _name:String, _address:String, _zip:String, _phone:String, _memberSince:String, _memberType:Char)
      {
        var number: Int = _number;
        var name: String = _name;
        var address: String = _address;
        var zip: String = _zip;
        var phone: String = _phone;
        var memberSince: String = _memberSince;
        var memberType: Char = _memberType;

    }

fun main(args: Array<String>) {



    var member1 = membership()
member1._number = 1
member1._name = "George Jetson";
member1._address ="123 Main St.";
member1._zip = "99207";
member1._memberSince = "12/01/1997";
member1._memberType = 'L';
}

Solution

  • You have declared the class membership with the primary constructor that expects 7 parameters. Hence, you need to provide values for these parameters when you're instantiating this class:

    var member1 = membership(
       _number = 1,
       _name = "George Jetson",
       _address ="123 Main St.",
       _zip = "99207",
       _memberSince = "12/01/1997",
       _memberType = 'L'
    )
    

    If you want to create an instance of the class first and then initialize its properties one-by-one, you need it to have a parameterless constructor:

    class membership() { 
    

    However then you'll have to make all its properties nullable or lateinit because now you cannot provide their initial values upon construction:

    class membership() {
       var number: Int? = null
       var name: String? = null
       var address: String? = null
       // etc
    }
    

    This way you'll be able to initialize them as you want in your question.