Kotlin object对象

2021-11-19  本文已影响0人  ZoranLee

Kotlin中没有静态属性和方法,但是可以使用关键字object声明一个object单例对象:


object UserInstance {

    val username: String = "admin"
    val password: String = "admin"
    fun hello() {
//        println("hello")
    }

}


//翻译成Java 具体实现单例方式
public final class UserInstance {
   @NotNull
   private static final String username = "admin";
   @NotNull
   private static final String password = "admin";
   public static final UserInstance INSTANCE;

   @NotNull
   public final String getUsername() {
      return username;
   }

   @NotNull
   public final String getPassword() {
      return password;
   }

   public final void hello() {
   }

   private UserInstance() {
   }

   static {
      UserInstance var0 = new UserInstance();
      INSTANCE = var0;
      username = "admin";
      password = "admin";
   }
}

companion object 伴生对象

class DataProcessor {
    companion object {
        fun process() {
            System.err.println("aaa")
        }
    }
}

fun main() {
    DataProcessor.process()
}

public final class DataProcessor {
   public static final DataProcessor.Companion Companion = new DataProcessor.Companion((DefaultConstructorMarker)null);

   @Metadata(
      mv = {1, 1, 13},
      bv = {1, 0, 3},
      k = 1,
      d1 = {"\u0000\u0012\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0002\n\u0002\u0010\u0002\n\u0000\b\u0086\u0003\u0018\u00002\u00020\u0001B\u0007\b\u0002¢\u0006\u0002\u0010\u0002J\u0006\u0010\u0003\u001a\u00020\u0004¨\u0006\u0005"},
      d2 = {"LDataProcessor$Companion;", "", "()V", "process", "", "idea_java"}
   )
   public static final class Companion {
      public final void process() {
         System.err.println("aaa");
      }

      private Companion() {
      }

      // $FF: synthetic method
      public Companion(DefaultConstructorMarker $constructor_marker) {
         this();
      }
   }
}

一个类只能有一个伴生对象。

上一篇下一篇

猜你喜欢

热点阅读