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”;
}
}
}
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"
}
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With