https://kotlinlang.org logo
Title
m

Mathbl

02/20/2018, 2:11 PM
My use case is: I have a singleton (kotlin object) and I would like to have a method
disconnect
that I could call from anywhere. Disconnect would check if
isConnected
and if not, will just do nothing. But the thing is, right now, if disconnect is the first method to be called on that object, it will call
init
before calling disconnect...and my init calls
connect()
on the object. So that's a bit counterproductive to connect then disconnect right after.
m

menegatti

02/20/2018, 2:25 PM
maybe companion objects?
m

Mathbl

02/20/2018, 2:27 PM
Can you have a companion object inside an object?
m

menegatti

02/20/2018, 2:30 PM
the problem is how to reference the method then
on a second thought, I’m not sure that’s possible
m

Mathbl

02/20/2018, 2:31 PM
I just tested and I don't think an object can hold a companion object. I did test an inner object, but it will still call init. Don't think it's possible indeed.
t

themishkun

02/20/2018, 3:19 PM
Dont you want to call
connect()
in some other method than
init
?
It would be better in terms of SRP
m

Mathbl

02/20/2018, 3:42 PM
That's what I ended up doing! It also make sense. 🙂
So init just sets some variables.