sealed class response<T>{
data class success <T> (value:T): Response <T>()
data class fail<T>(valueerrorMessage: String):Response<T>()
}
fun<T>fetch(onResponse:(Response<T>)->Unit){
value —T
// get something and put it in the value
onResponse(Response.Success(value))
}
I made a process like this, but
About T
in Response
Type Parameter "T" is never used
warning appears
(In fact, T
in Response
is not related to the T
in that child class.)
If you don't want to use the variable type parameter itself, but you want the class to be generic, is there a good way to write ?
The process itself works fine.
kotlin generics
It's probably inconvenient as it is, and it usually defines some kind of function, so I don't think that problem will occur.
sealed class Response <out T>{
fun<A>map(f:(T)-> A)—Response <A>{
return when (this) {
is Success ->Success(f(value))
is Fail->this
}
}
data class success <T> (value:T): Response <T>()
data class fail (value errorMessage: String): Response <Nothing > ( )
}
data class User (val name: String, value: Int)
fun fetch(onResponse:(Response <User>) - > Unit) {
value result=Response.Success(mapOf("name" to "John", "age" to "42"))
onResponse(
result.map {
User(it.getValue("name"), it.getValue("age").toInt())
}
)
}
However, if you really don't use it or define a function as an extension such as kotlin-either, you should use @Suppress("unused")
because the type parameter is determined to be unused.
https://github.com/adelnizamutdinov/kotlin-either/blob/master/src/main/kotlin/either/Either.kt
@Suppress("unused")
sealed class Either <out L,out R>
In addition, the Result
type introduced from Kotlin 1.3 does not define the Success
type and determines it as success if it is not a Failure
that has no inheritance relationship with the Result
.
https://github.com/JetBrains/kotlin/blob/1.3.0/libraries/stdlib/coroutines/src/kotlin/Result.kt
@SinceKotlin("1.3")
public inline class Result <out T>@PublishedApi internal constructor(
@PublishedApi
internal value —Any?
)—Serializable {
// discovery
/**
* Returns `true` if this instance presents successful outcome.
* In this case [isFailure] returns `false'.
*/
public value isSuccess: Boolean get() = value! is Failure
/**
* Returns `true` if this instance presents failed out.
* In this case [isSuccess] returns `false'.
*/
public value isFailure: Boolean get() = value is Failure
internal class Failure(
@JvmField
val exception —Throwable
)—Serializable {
override fun equals (other: Any?): Boolean=other is Failure&&exception==other.exception
override fun hashCode(): Int=exception.hashCode()
override fun to String(): String="Failure($exception)"
}
581 PHP ssh2_scp_send fails to send files as intended
611 GDB gets version error when attempting to debug with the Presense SDK (IDE)
572 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
914 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
© 2024 OneMinuteCode. All rights reserved.