Skip to main content

Posts

Showing posts with the label dynamic objects

anonymous objects in Kotlin

Anonymous Objects The benefit of using the anonymous objects is that they can be used to simplify usage rather than creating classes and then instantiating them and then consuming the functions. In this post, we are taking a simple interface and the interface is being used as an argument in a function. When we need to consume the method, we are required to create objects that are created from the classes that implement the interfaces. interface IPowerOfTwo { fun getPowerOf2 ( no : Int ): Int } fun printPowerOf2 ( powerOf2 : IPowerOfTwo ) { println ( "The value ^ 2 is : ${ powerOf2 .getPowerOf2(20) } " ) } Rather than creating the classes and instances, we can create an object on the fly and pass it as an argument to the function. fun main () { //The below method uses an anonymous object that has no class, yet implements the interface and gets the method ready for use printPowerOf2 ( object : IPowerOfTwo { override fun getPowerOf2 ( no : Int ) = no * n