https://kotlinlang.org logo
#announcements
Title
# announcements
z

zceejkr

10/28/2019, 11:47 AM
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

devbridie

10/28/2019, 11:51 AM
companion object { val thing = someFunc() }
is the closest you can get
z

zceejkr

10/28/2019, 11:54 AM
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

marstran

10/28/2019, 11:57 AM
Maybe
companion object : SomeType by someFunc()
works?
❤️ 2
👏 1
w

wbertan

10/28/2019, 11:57 AM
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

zceejkr

10/28/2019, 11:58 AM
@marstran this is exactly it! many thanks
👍 1
@wbertan I guess yours is the same suggestion. Thank you also!
k

karelpeeters

10/28/2019, 12:02 PM
You can also just use an abstract class as a base class for a companion object, so delegation may not even be necessary.
4 Views