Is it possible to make a companion object equal to...
# announcements
z
Is it possible to make a companion object equal to the output of some function? I am trying to do something like
companion object : SomeType = someFunc()
. Or do you always have to declare the companion, as in
companion object : SomeType {body}
?
👍 1
d
companion object { val thing = someFunc() }
is the closest you can get
z
So the problem I have is I have a generic type Decoder<A>, and I want to make the companion object of “decodable” data classes (A) an instance of Decoder<A>. I also have combinators for making these decoders, so for more complex data classes I want to construct the Decoder instance by using the combinators and the Decoders of the simpler data classes. Is there a nice way of doing this?
m
Maybe
companion object : SomeType by someFunc()
works?
❤️ 2
👏 1
w
You can do something like:
Copy code
typealias SomeType = () -> String

fun someFunc(): String = "asas"

object Asas : SomeType by ::someFunc

class ExampleUnitTest {
    @Test
    fun asas() {
        assertEquals("asas", Asas())
    }
}
By the way, I didn’t tested 😆
👍 1
z
@marstran this is exactly it! many thanks
👍 1
@wbertan I guess yours is the same suggestion. Thank you also!
k
You can also just use an abstract class as a base class for a companion object, so delegation may not even be necessary.