I was wondering if I can use a property of a class inside a companion object. for example take the instance bellow:
class Person1(val name: String, var age: Int){
lateinit var surname: String
companion object myc{
var cname: String =""
var cage: Int = 0
fun constructor(cname: String, cage: Int){
this.cage = cage
this.cname = cname
}
fun changeAge(age: Int ?= 0){
// access to surname or name or age
}
}
}
i can't get access to any of the properties from Person1 class
and for instance lets say that we call the class or companion object as bellow:
val c1 = Person1.myc.constructor("john",10)
val c2= Person1("jack",20)
i can't call the changeAge() function through c1 or c2. the only place where i can use changeAge is through Person1.changeAge() when Person1 has not been instantiated with proper constructor. i was wondering if there is an alternative for these actions or if there aren't what is the point of having companion objects anyways
Person
class. – Marko Topolnik