This post demonstrates how to create static class members similar to that of Java
. We use Kotlin 1.1
here.
All static members Class
If we want to create a class that only contains static members, we use singletons in Kotlin
. For example:
[wp_ad_camp_1]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | package com.turreta.kotlin /** * Created by Turreta.com on 20/6/2017. */ object AllStaticMembersClass { // Don't allow change val applicationName: String = "SuperKotlinDemo App" var numberOfUsers: Int = 0 } // main function fun main(args: Array<String>) { println(AllStaticMembersClass.applicationName) println(AllStaticMembersClass.numberOfUsers) AllStaticMembersClass.numberOfUsers = 10 println(AllStaticMembersClass.numberOfUsers) } |
Outputs:
1 2 3 | SuperKotlinDemo App 0 10 |
Static and non-static members in class
[wp_ad_camp_2]
Sometimes we have classes that have both static and non-static class members in Java
. In Kotlin
, we can mix static and non-static members in one class. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | package com.turreta.kotlin /** * Created by Turreta.com on 20/6/2017. */ class NonStaticAndStaticMembersClass { // Don't allow change val applicationName: String = "SuperKotlinDemo App" companion object { var numberOfUsers: Int = 0 fun showAbout() { println("About...") } } } // main function fun main(args: Array<String>) { var o: NonStaticAndStaticMembersClass = NonStaticAndStaticMembersClass() println(o.applicationName) println(NonStaticAndStaticMembersClass.numberOfUsers) NonStaticAndStaticMembersClass.numberOfUsers = 15 println(NonStaticAndStaticMembersClass.numberOfUsers) NonStaticAndStaticMembersClass.showAbout() } |
Outputs:
[wp_ad_camp_3]
1 2 3 4 | SuperKotlinDemo App 0 15 About... |
References
https://kotlinlang.org/docs/reference/classes.html