Home > Enterprise >  how to initialize data to variable with same name as constructor variables
how to initialize data to variable with same name as constructor variables

Time:12-07

I have a variable foo:String declared in kotlin and in constructor i want to pass variables with same name as foo:String but i don,t know how to make both variables different from each other as in c# we use this.foo for class variables

i am expecting

class Product
{
    lateinit var productName:String
    constructor(productName:String)
    {
        this.productName = productName
    }
}

please guide me how to do it in kotlin

CodePudding user response:

That entire class can be written as just

class Product(var productName: String)

CodePudding user response:

You use this like you used in C#

This sample shows how to do this for primary constructor

class Product{
   private val name : String
   constructor(name : String) {
      this.name = name
   }
}

And this is sample for second constructor:

class Product (){
    private var name : String = ""
    constructor(name : String) : this() {
        this.name = name
    }
}
  • Related