0

Below one is the kotlin code. I just want same thing in java how can i do that

sealed class NetworkResult<T>(val data: T? = null, val message: String? = null) {
    class Success<T>(data: T) : NetworkResult<T>(data)
    class Error<T>(message: String?, data: T? = null) : NetworkResult<T>(data, message)
    class Loading<T> : NetworkResult<T>()
}

I tried with the below one but was not able to access the inner class. Try to access this NetworkResult.Success(response.body()) but getting error 'Method call expected'

class NetworkResult <T>{
    private String message;
    private T data;
    public NetworkResult(T data,String message) {
        this.data=data;
        this.message=message;
    }
    public NetworkResult(T data) {
        this.data=data;
    }

    public NetworkResult() {
    }

    class Success<T> extends NetworkResult<T>{
        public Success(T data) {
            super(data);
        }
    }
    class Error<T> extends NetworkResult<T>{

        public Error(T data, String message) {
            super(data, message);
        }
    }

    class Loading<T> extends NetworkResult<T>{

    }
}

  • Does https://subscription.packtpub.com/book/application-development/9781788472142/1/ch01lvl1sec17/converting-java-code-to-kotlin-and-vice-versa answers your question? It is not a nice way but it should work, – Reporter Dec 30 '22 at 12:18
  • 2
    I think you need to declare the inner classes static, for example `static class Success extends NetworkResult{`. And then you need to use the `new` keyword in Java, for example `new NetworkResult.Success("dummy")`. That should do it. – Ole V.V. Dec 30 '22 at 12:26
  • Does this answer your question? [Naming Classes - How to avoid calling everything a "Manager"?](https://stackoverflow.com/questions/1866794/naming-classes-how-to-avoid-calling-everything-a-whatevermanager) – Hooman.AS Dec 30 '22 at 12:32
  • That is a poorly designed sealed class in Kotlin. It defeats the purpose of having a sealed class if all of the possible uses are already in the base class as nullable properties. You end up having to do null checks and get no benefits from smart-casting. You just have extra class hierarchy for no reason. It becomes even worse if you translate it to Java, where you can't even mark the hierarchy as sealed. – Tenfour04 Dec 30 '22 at 16:53

0 Answers0