https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

dave08

12/22/2021, 12:15 PM
If I have:
Copy code
sealed interface Foo<R>
object NoFoo : Foo<Nothing>
data class SomeFoo<R> : Foo<R>

// Is there any way this could work? (It doesn't... even though I don't use the R in NoFoo)
val baz: Foo<Baz> = NoFoo
r

Rob Elliot

12/22/2021, 12:56 PM
Try using
<out R>
Copy code
sealed interface Foo<out R>
object NoFoo : Foo<Nothing>
data class SomeFoo<out R>(val r: R) : Foo<R>
interface Baz

val baz: Foo<Baz> = NoFoo
d

dave08

12/22/2021, 1:09 PM
Thanks! I still have a bit of trouble with all this covariance etc... It seems in my case I had to use
in
with
Any
instead of
Nothing
...
r

Rob Elliot

12/22/2021, 1:40 PM
Without know your real use case it's hard to comment...
in Any
sounds like a pretty useless type.
d

dave08

12/22/2021, 1:43 PM
I don't really need it in that object... my use case is a bit complicated... I need that as a return type from a callback
() -> Foo<SomeType>
then, if I have a
SomeFoo
as a result of that callback, then I need it in something like
setResult(someFoo.value)
r

Rob Elliot

12/22/2021, 1:56 PM
Would this help?
Copy code
sealed interface Foo<out R> {
  val value: R
}
object NoFoo : Foo<Nothing> {
  override val value: Nothing
    get() = error("unsupported")
}

data class SomeFoo<out R>(override val value: R) : Foo<R>
Slack is refusing to let me edit that...
Copy code
val foo: Foo<String> = TODO()
if (foo is SomeFoo) {
  setResult(foo.value)
}
Alternatively, are you sure you aren't reinventing
kotlin.Result
?
d

dave08

12/22/2021, 5:01 PM
I'm not... I have three possibilities 1) Don't change anything, 2) Set a new value (including setting to null), 3) Set an exception (that was caught).
kotlin.Result
only has the last two...
I wonder if having that
<Any>
there is so bad... compared to the alternatives that are much more verbose...?
I can't edit my posts either @Alina Dolgikh [JB]... it seems like someone restricted editing posts on this slack...
Or maybe they're just having problems now?