java - 如何将密封的 Kotlin 类转换为 Java 类

标签 java android kotlin

我想知道 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/

相关文章:

java - java中的异常是什么?

java - Selenium WebDriver Firefox 错误 - 连接失败

java - 动画后我无法清除我的 ImageView

android - Xamarin 安卓 : Will SyncAdapter ever expired during calling

java - 删除 ArrayList 中所有出现的第一个元素

java - 在 spring mvc 中将文件名传递给 Controller

android - Kotlin 协程阻塞 Android 中的主线程

android - RecyclerView中的 session 室数据库条目

android - 什么是 com.android.externalstorage?

java - 设计困境——背景还是契约? (Java/ Kotlin )