Gerard Bosch
04/29/2021, 5:25 PMUnresolved reference: of
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!Nir
04/29/2021, 5:28 PMNir
04/29/2021, 5:28 PMHolden Easley
04/29/2021, 5:28 PMof
is a member function of Seal
so you need to make it accessible without an instance of Seal
using one of the methods mentioned aboveNir
04/29/2021, 5:29 PMNir
04/29/2021, 5:29 PMGerard Bosch
04/29/2021, 5:32 PMSealed.of()
if possible. The companion object did the job, thank you! 😃Nir
04/29/2021, 5:32 PMNir
04/29/2021, 5:32 PMcall
operator for the companion object, those are actually called "smart constructors"Nir
04/29/2021, 5:33 PMSealed(foo)
) but it actually calls a functionNir
04/29/2021, 5:33 PMGerard Bosch
04/29/2021, 5:33 PMGerard Bosch
04/29/2021, 5:33 PMNir
04/29/2021, 5:33 PMinvoke
, not call
Gerard Bosch
04/29/2021, 5:34 PMNir
04/29/2021, 5:34 PMtodd.ginsberg
04/29/2021, 6:34 PMephemient
04/29/2021, 6:45 PMoperator fun invoke()
- no magic without the right keywords 🙂ephemient
04/29/2021, 6:47 PMfun Sealed(n: Int) = if (n > 0) Sealed.Foo("test") else Sealed.Bar(42)
ephemient
04/29/2021, 6:48 PMList()
etc.Gerard Bosch
04/29/2021, 6:48 PMephemient
04/29/2021, 6:49 PMprivate
within the class though, only companion object
will work, because that will have accessGerard Bosch
04/29/2021, 6:49 PMoperator invoke
or of()
Nir
04/29/2021, 6:49 PM