Hi there, is it possible to do this in Kotlin some...
# announcements
g
Hi there, is it possible to do this in Kotlin somehow? (it is just an example) I get error at call-site:
Unresolved reference: of
Copy code
sealed class Sealed {
    
    // Is it possible to define a factory method or smart constructor here?
    fun of(n: Int): Sealed = if (n > 0) Foo("test") else Bar(42)
    
    data class Foo(val str: String) : Sealed()
    data class Bar(val num: Number) : Sealed()
}
and why is the above not possible? thank you!
n
You would define such a function on an anonymous companion
👍 1
Or you could just define a top level function outside the class
h
^^
of
is a member function of
Seal
so you need to make it accessible without an instance of
Seal
using one of the methods mentioned above
n
Right. Even if that worked, it wouldn't do what you probably want it to. Beyond that, there may be restrictions on sealed classes, I've never actually tried to use one like that so I'm not sure
A constructor cannot be polymorphic, I expect, it needs to know statically what type it's constructing
g
It works with a top level function outside the clas yes, but I wanted to qualify the call as
Sealed.of()
if possible. The companion object did the job, thank you! 😃
n
np
btw, when you define the
call
operator for the companion object, those are actually called "smart constructors"
because it looks just like a constructor call (
Sealed(foo)
) but it actually calls a function
so you can do things that you can't in a normal constructor, i.e. polymorphic return, generic
g
Nice! thank you
Happy to learn 🙂
n
Sorry,
invoke
, not
call
g
ah, yes invoke, that makes sense, I see
n
np 🙂
t
Didn’t know that pattern had a name. Thanks Nir! :)
e
operator fun invoke()
- no magic without the right keywords 🙂
you can also name a top-level function the same as the class, e.g.
Copy code
fun Sealed(n: Int) = if (n > 0) Sealed.Foo("test") else Sealed.Bar(42)
used in the standard library,
List()
etc.
☝️ 1
g
Oh, good idea, yes 🙂
e
if you rely on anything
private
within the class though, only
companion object
will work, because that will have access
👍 2
g
I think I like even more than
operator invoke
or
of()
n
Yeah, a top level function is ideal, it's the simplest, assuming you don't need the private access