Kotlin Constructors
Constructor of class are used to initialize and set primary values of data member. kotlin is support two type of constructor. primary and secondary constructor.
Primary constructor
//example of primary constructor
class Mobile(var type:String, var price:Float){
fun getInfo(){
println(" type : $type and price $price")
}
}
fun main(args: Array){
//set class data member values
var smart=Mobile("Smart Phone",10000f)
var basic=Mobile("Basic Phone",2000f)
smart.getInfo()
basic.getInfo()
}
Output
Type : Smart Phone Price : 10000.0
Type : Basic Phone Price : 2000.0
Secondary constructor
class Mobile{
var type:String
var price:Float
//constructor of class
constructor(typeInfo:String,priceAmount:Float) {
type=typeInfo
price=priceAmount
}
fun itemData(){
println("Type : $type Price : $price")
}
}
fun main(args: Array<String>){
//set class data member values
var smart=Mobile("Smart Phone",10000f)
var basic=Mobile("Basic Phone",2000f)
smart.itemData()
basic.itemData()
}
Output
Type : Smart Phone Price : 10000.0
Type : Basic Phone Price : 2000.0
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment