Kotlin Constant and Static Method

Posted by LucidParody on Sun, 13 Oct 2019 20:38:01 +0200

constant

Java:

   class StaticDemoActivity {
         public static final String LOAN_TYPE = "loanType";
         public static final String LOAN_TITLE = "loanTitle";
    }

Kotlin:

  class StaticDemoActivity {
      companion object {
           val  LOAN_TYPE = "loanType"
           val  LOAN_TITLE = "loanTitle"
    }
}

//perhaps

  class StaticDemoActivity {
      companion object StaticParams{
            val  LOAN_TYPE = "loanType"
            val  LOAN_TITLE = "loanTitle"
    }
}

 //perhaps
  class StaticDemoActivity {
      companion object {
         const val LOAN_TYPE = "loanType"
         const val LOAN_TITLE = "loanTitle"
    }
}

Note: The const keyword is used to modify constants, and can only modify val, not var. The name of companion object can be omitted and can be referred to by Companion.

Reference constants (references here are only for java references to kotlin code)

The TestEntity class references constants in StaticDemoActivity

   class TestEntity {
        public TestEntity () {
            String title = StaticDemoActivity.Companion.getLOAN_TITLE();
    }
  }

  //perhaps

  class TestEntity {
        public TestEntity () {
            String title = StaticDemoActivity.StaticParams.getLOAN_TITLE();
        }
  }

  //perhaps

  class TestEntity {
        public TestEntity () {
            String title = StaticDemoActivity.LOAN_TITLE;
            String type= StaticDemoActivity.LOAN_TYPE;
        }
  }

Static method

Java code:

      class StaticDemoActivity {
          public static void test(){
                ,,,
          } 
      }

Kotlin:

      class StaticDemoActivity {
          companion object {
               fun test(){
                    ,,,
                }
          }
      }

  //perhaps

       class StaticDemoActivity {
          companion object StaticParams{
              fun test() {
                  ,,,
              }
          }
      }

Reference to static methods (references here are only for java reference to kotlin code)

The TestEntity class references static methods in StaticDemoActivity

    class TestEntity {
          public TestEntity () {
                StaticDemoActivity.Companion.test();
          }
    }

//perhaps

    class TestEntity {
          public TestEntity () {
             StaticDemoActivity.StaticParams.test();
          }
    }

The companion object {} modifies static constants, or static methods, singletons, etc.

Topics: Java