Emil Kantis
03/20/2025, 4:45 PMfun <T> bar() = object : Bar<T> {
// ..
}
object Foo = bar<Int>()
Youssef Shoaib [MOD]
03/20/2025, 4:46 PMval Foo = bar<Int>()
ephemient
03/20/2025, 5:24 PMobject Foo : Bar<T> by bar()
Emil Kantis
03/20/2025, 5:27 PMBar<T>
is an abstract class from a library, so delegation is a no-go.
And I need to reference it by Foo::class
, again due to working with this library, so a simple val
won't do 😞ephemient
03/20/2025, 5:32 PMbar()
then perhaps, but for now no.Emil Kantis
03/20/2025, 6:07 PMephemient
03/20/2025, 6:13 PMephemient
03/20/2025, 6:13 PMWout Werkman
03/22/2025, 5:20 PMNothing
. Let's take the example of Java's Collections.emptyList()
for example.
Practically, what Java has here is the following:
object EmptyList: List<Any?> { ... }
object Collections {
fun <T> emptyList() = EmptyList as List<T> // This code is not safe!
}
functionThatTakesListOfInt(EmptyList) // Compiler error
functionThatTakesListOfInt(Collections.emptyList()) // Java's workaround
Luckily, in Kotlin you have Nothing
, because List
is covariant on T
(annoying smart people words for T
being out T
).
So you can simply declare:
object EmptyList: List<Nothing> { ... }
functionThatTakesListOfInt(EmptyList) // Yay, works!
So if your Bar<T>
is abstract class Bar<out T>
, then you might be able to make it typesafe as object Foo: Bar<Nothing>() { ... }
Youssef Shoaib [MOD]
03/22/2025, 6:57 PM