Is there any way to create a named object using a ...
# getting-started
e
Is there any way to create a named object using a function that returns an anonymous object?
Copy code
fun <T> bar() = object : Bar<T> {
  // ..
}

object Foo = bar<Int>()
1
y
I don't think so, but you can at least place it in a `val`:
Copy code
val Foo = bar<Int>()
e
this would also be close but not quite the same
Copy code
object Foo : Bar<T> by bar()
e
In my case,
Bar<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 😞
e
then if https://youtrack.jetbrains.com/issue/KT-30915/Inline-constructors were implemented and you used that instead of
bar()
then perhaps, but for now no.
e
Thanks for the confirmation. Not sure how the inline constructors would help, but I starred and upvoted those issues. 🙂
e
assuming you could define constructors externally, since they'd be inlined into the caller anyway…
well it's a wishful thought anyhow. I'm not sure the language will evolve in that way
w
It depends on the use case. If the program is truly safe, there is a good chance that you can get away with
Nothing
. Let's take the example of Java's
Collections.emptyList()
for example. Practically, what Java has here is the following:
Copy code
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:
Copy code
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>() { ... }
y
@Wout Werkman I think you might've posted this in the wrong thread lol!