xxxxxxxxxx
class Test {
companion object {
var mInteger: Int = 10
fun hello() = println("hello world !")
}
}
fun main(args: Array<String>) {
print(Test.mInteger)
print(Test.hello())
}
xxxxxxxxxx
In Kotlin, if you want to write a function or any member of the class that
can be called without having the instance of the class then you can write
the same as a member of a companion object inside the class.
class Comp{
companion object {
val tag = "MY_TAG"
fun sum(i:Int , j:Int) = println(i+j)
}
}
xxxxxxxxxx
class Person {
companion object Test {
fun callMe() = println("I'm called.")
}
}
fun main(args: Array<String>) {
Person.callMe()
}
xxxxxxxxxx
class Person {
fun callMe() = println("I'm called.")
}
fun main(args: Array<String>) {
val p1 = Person()
// calling callMe() method using object p1
p1.callMe()
}