I couldn’t find anything but is there a way to ass...
# announcements
I couldn’t find anything but is there a way to assign to itself in the constructor of a class ? For the sake of simplification let’s say I have
Copy code
class Dog{
    val name:String
    val age:Int

    init { this = fetchDogFromSomewhere() }

fun fetchDogFromSomewhere():Dog{ 
   // Things
Is there some way to achieve this? Right now I’m using a companion method that calls fetchDogFromSomwhere
🚨 I’m getting some big X-Y problem vibes from this question
what are you trying to achieve by reassigning the value of
sounds almost like you have a singleton? like you only want one instance of
and you’d like for folks to receive the same instance if they try to instantiate one?
If it actually gets instantiated in the constructor, how would the first instance ever be able to be created? It’s a chicken-and-egg problem.
👆 1
You could give the appearance of invoking a constructor with
operator fun invoke()
in the companion object, which is about as good as you could get https://pl.kotl.in/EV4wuPggt
true, if you just want a factory method to be responsible for instantiation, make the constructor private and implement the method in the companion object - whether you implement
or give it a more descriptive name is up to you
You'll need to be clearer about your objectives. Is there only one instance of Dog for the whole of your program? That's a singleton. Are you trying to potentially return a subclass of Dog? That's an abstract factory. Is there a network request that is serializing your object? You may need to dig down into things like readResolve.. Not sure if that one is applicable to Kotlin though.