DEV Community

qiudaozhang
qiudaozhang

Posted on

3 3

kotlin data class 看下反编译的代码

kotlin

data class IdModel(val id: String)
Enter fullscreen mode Exit fullscreen mode

对应的class文件反编译查看为

import kotlin.Metadata;
import kotlin.jvm.internal.Intrinsics;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

@Metadata(mv = {1, 7, 1}, k = 1, xi = 48, d1 = {"\000\"\n\002\030\002\n\002\020\000\n\000\n\002\020\016\n\002\b\006\n\002\020\013\n\002\b\002\n\002\020\b\n\002\b\002\b\b\030\0002\0020\001B\r\022\006\020\002\032\0020\003\006\002\020\004J\t\020\007\032\0020\003H\003J\023\020\b\032\0020\0002\b\b\002\020\002\032\0020\003H\001J\023\020\t\032\0020\n2\b\020\013\032\004\030\0010\001H\003J\t\020\f\032\0020\rH\001J\t\020\016\032\0020\003H\001R\021\020\002\032\0020\003\006\b\n\000\032\004\b\005\020\006\006\017"}, d2 = {"Lbasic/IdModel;", "", "id", "", "(Ljava/lang/String;)V", "getId", "()Ljava/lang/String;", "component1", "copy", "equals", "", "other", "hashCode", "", "toString", "exposed_tutorial"})
public final class IdModel {
  @NotNull
  private final String id;

  public IdModel(@NotNull String id) {
    this.id = id;
  }

  @NotNull
  public final String getId() {
    return this.id;
  }

  @NotNull
  public final String component1() {
    return this.id;
  }

  @NotNull
  public final IdModel copy(@NotNull String id) {
    Intrinsics.checkNotNullParameter(id, "id");
    return new IdModel(id);
  }

  @NotNull
  public String toString() {
    return "IdModel(id=" + this.id + ')';
  }

  public int hashCode() {
    return this.id.hashCode();
  }

  public boolean equals(@Nullable Object other) {
    if (this == other)
      return true; 
    if (!(other instanceof IdModel))
      return false; 
    IdModel idModel = (IdModel)other;
    return !!Intrinsics.areEqual(this.id, idModel.id);
  }
}
Enter fullscreen mode Exit fullscreen mode

在类的基础上自动添加了很多方法,同时也把class标记为了final,不可继承,这就有个问题, 我们又希望使用data class的便利,还想继承怎么搞,比如在mongodb里面我可能需要基础的class,记录了id和created,updated时间,如果每个类都搞一下,岂不是很烦人。

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay