Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how make multiple sub set constant in kotlin

In java having a class which defines a few constants, some are in the inner class.

They could be referred as:

Data.HTTP_SCHEME;
Data.Constants.ResponseType.XML;
Data.PayloadType.JSON

How to do the same in Kotlin?

public class Data {
public static final String HTTP_SCHEME = "http";
public static final String HTTPS_SCHEME = "https";

public static class Constants {

    public static class ResponseType {
        public static final String XML = "xml";
        public static final String JSON = "json";
    }        
    public static class PayloadType {
        public static final String JSON = "json";
    }

    public static class ItemDataType {
        public static final String ID = "id";
        public static final String IS_GLOBAL = "isGlobal";
        public static final String IS_TRANSLATED = "isTranslated”;
    }
}
}
like image 237
lannyf Avatar asked Jan 29 '23 12:01

lannyf


2 Answers

Unlike Java Kotlin does not have static variables. Instead they have companion objects. Every class comes with a companion object which you can use to store your static values.

class Constants {

    companion object {
        val HTTP_SCHEME = "http"
        val HTTPS_SCHEME = "https"
    }
}

fun main(args: Array<String>) {
    println(Constants.HTTP_SCHEME)
    println(Constants.HTTPS_SCHEME)
}

Or if you want to group your static values together you can create non companion object

class Constants {

    companion object {
        var HTTP_SCHEME = "http"
        var HTTPS_SCHEME = "https"
    }

    object ResponseType {
        val XML = "xml"
        val JSON = "json"
    }
    object PayloadType {
        val JSON = "json"
    }

    object ItemDataType {
        val ID = "id"
        val IS_GLOBAL = "isGlobal"
        val IS_TRANSLATED = "isTranslated"
    }

}

fun main(args: Array<String>) {
    println(Constants.ItemDataType.IS_TRANSLATED)
    println(Constants.PayloadType.JSON)
}

If you want your companion object values to be exposed as static to some Java classes you can annotate them with @JvmStatic

class Constants {

    companion object {
        @JvmStatic var HTTP_SCHEME = "http"
        @JvmStatic var HTTPS_SCHEME = "https"
    }
}
like image 194
JavaBanana Avatar answered Feb 01 '23 02:02

JavaBanana


You can use below code :

object Data {
  val HTTP_SCHEME = "http"
  val HTTPS_SCHEME = "https"
  class Constants {
    object ResponseType {
      val XML = "xml"
      val JSON = "json"
    }
    object PayloadType {
      val JSON = "json"
    }
    object ItemDataType {
      val ID = "id"
      val IS_GLOBAL = "isGlobal";
      val IS_TRANSLATED = "isTranslated”;
    }
  }
}

Explanation:

In Kotlin object keyword is used create static class ( like in java).

like image 41
pRaNaY Avatar answered Feb 01 '23 03:02

pRaNaY