I don't understand what these lines inside when do...
# android
m
I don't understand what these lines inside when do. Would someone mind explaning a bit to me?
Copy code
override fun toString(): String {
    return when (this) {
        is Success<*> -> "Success[data=$data]"
        is Error -> "Error[exception=$exception]"
    }
}
This is from the template Login Activity in Android Studio. What is Success<*> and what is "Success[data=$data]"?
l
Basically,
this
can be an instance of either Success, or Error. You are checking whether you have an instance of one or the other. The thing is that your class is generic. You can have a
Success<Int>
, or a
Success<String>
for example. In this case, you don't care whether you have Int or String, you want to match any Success, hence the wildcard
<*>
1
m
So what is the Success[data...] part?
p
It returns a string with the datas to string implementation
1
v
Success is an array, so saying Success[data=$data] is saying you want the data (the info aka the stuff that is important in the scenario)
1
r
Just to clarify, success is not an array. That part is just a string whose syntax does not represent the structure of the data. This appears to be something like a sealed class or some kind of base class. Based on the syntax here, we can tell that this is probably something like
Copy code
sealed class Result<T>(
    val data: T?
    val exception: Exception?
) {
    class Success<T>(data: T): Result<T>(data, null)
    class Error(exception: Exception): Result<Nothing>(null, exception)
}
Given
Success(14).toString()
, we can expect an output of
Success[data=14]
. Given
Success("foo").toString()
, we can expect an output of
Success[data=foo]
. Given
Error(Exception("foo"))
, we can expect an output of
Error[exception=java.lang.Exception: foo]
The
$varName
syntax is called string interpolation. it takes the variable supplied, calls the
toString
function on it, and inserts that string into the string literal that contains it. Hope that helps @Mehdi Haghgoo
1
m
Thank you @rook I just saw your reply.