如何使多个子集在kotlin中保持不变

时间:2017-09-25 00:29:22

标签: android kotlin constants

在java中有一个定义了几个常量的类,有些是在内部类中。

他们可以被称为:

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

如何在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”;
    }
}
}

3 个答案:

答案 0 :(得分:3)

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"
    }
}

答案 1 :(得分:2)

您可以使用以下代码:

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”;
    }
  }
}

说明:

在Kotlin中object使用关键字创建静态类(如在java中)。

答案 2 :(得分:1)

这很简单,你可以定义如下:

class A{
    class ResponseType {
        companion object { 
             val code = 100 // you can call: A.ResponseType.code in everywhere now
        }
    }
}