companion object

4 0 0
                                        

object - If you use an object, you do not need to create an instance of the class you are using. Instead, you just use the class name followed by the object name and then the method that you want to invoke inside this object. Though the problem is you cannot access the properties and parameters of your class. This is a like creating a single class within that your class.

syntax:

class FirstClass{

    object Name{

        fun methodName(){ // statement }

    }

}

companion - This is use together with your object. Telling the compiler that this object is a companion of the class. If you use companion on an object inside your class, you can omit the object name. Just the name of the class will do to call the method inside that companion object you created.

syntax:

class SecondClass{

    companion object{

        fun methodName(){ // statement}

    }

}


If you invoke both syntax in a main:

fun main(){

    FirstClass.Name.methodName()

    SecondClass.methodName()

}

==================  

abstract class FourSides(var length: Double=0.0, var width: Double=0.0){

    abstract fun getArea(): Double

    companion object{

        fun perimeter(l: Double, w: Double) = (2 * l) + (2 * w)

    }

}

class Rectangle: FourSides(){

     private var rectanglePerimeter = 0.0

     object TestingObjectOnly{

         fun justATest(){

             println("Testing Object")

         }

     }

     fun setLengthAndWidth(){

         val scanner = Scanner(System.'in')

         print("Enter number in Double: ")

         length = scanner.nextDouble()

         print("Enter number in Double: ")

         width = scanner.nextDouble()

         rectanglePerimeter = perimeter(length, width)

     }

     override fun getArea(): Double{

          return length * width

     }

     fun displayRectangle(){

         println("Area: ${getArea()}")

         println("Perimeter: $rectanglePerimeter")

     }

}

fun main(){

     Rectangle.TestingObjectOnly.justATest()

     val obj = Rectangle()

     obj.setLengthAndWidth()

     obj.displatRectangle()

}

===================

Result:

Testing Object

Enter number in Double: 5.25

Enter number in Double: 5.25

Area: 27.5625

Perimeter: 21.0


Note: This is just a test of how companion works. There was slight intro about companion object and i just tried it in the IDE to know how it works. companion object will be when we reach Objects in kotlin tutorial.


Kotlin ProgrammingWhere stories live. Discover now