How to create static variables and methods in Kotlin?

In this article, we are going to learn how to create static variable and methods in Kotlin? Here is an example: program to count number of objects of a class.
Submitted by Aman Gautam, on January 29, 2018

Static members are those which are independent of the objects. They are associated with the class not with any particular object. There will be only single copy of static members whether any number of objects are created. So in this article we will learn how to create static members in kotlin.

In java, we create static member as:

class statik{
	static intcount;
		//constructor
		statik(){
		count++;
	}
	static voidgetCount(){
		System.out.println("No. of objects="+count);
	}
}
public class ExStatic{
	public static void main(String[] args) {
		//object 1
		new statik(); 
		// object 2
		new statik();   
		//method called using class name
		statik.getCount();    
	}
}

Output

No. of objects=2

In kotlin we will use companion object to create static members of the class.

An object declaration inside a class can be marked with the companion keyword. Members of the companion object can be called by using simply the class name,

companion object {
	var count:Int=0;
}

This is similar to

static int count;

Consider this program in which we have created a variable count and a method getcount() inside companion object block, which works similar to java program written above.

class statik{
	companion object {
		// static count 
		var count:Int=0;
		// ataticgetCount()
		fun getCount(){
			print("No. of objects="+count)
		}
	}
	//constructor
	constructor(){
		count++
	}
}

fun main(args: Array<String>) {
	//object 1
	statik()      
	// object 2
	statik()	
	//method called using class name
	statik.getCount()
}

Output

No. of objects=2



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.