我想知道 Java 代码中是否有这个 kotlin 密封类的等效项
sealed class Resource<out T> {
class Loading<out T> : Resource<T>()
data class Success<out T>(val data: T) : Resource<T>()
data class Failure<out T>(val exception: Exception) : Resource<T>()
}
最佳答案
这是我在 Java 项目中使用的:
public class State<T> {
// States, use enums if possible
public static final int INITIAL = 0;
public static final int LOADING = 1;
public static final int SUCCESS = 2;
public static final int ERROR = 3;
private final int type;
private final T data;
private final Throwable error;
private State(@NonNull int type, @Nullable T d, @Nullable Throwable e) {
this.type = type;
this.data = d;
this.error = e;
}
public static <T> State<T> initial() {
return new State<>(INITIAL, null, null);
}
public static <T> State<T> loading() {
return new State<>(LOADING, null, null);
}
public static <T> State<T> success(T d) {
return new State<>(SUCCESS, d, null);
}
public static <T> State<T> error(Throwable e) {
return new State<>(ERROR, null, e);
}
public int getType() {
return type;
}
public T getData() {
return data;
}
public Throwable getError() {
return error;
}
}
关于java - 如何将密封的 Kotlin 类转换为 Java 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63427640/