Hi everyone, glad to be here. I am trying to creat...
# getting-started
s
Hi everyone, glad to be here. I am trying to create an extension property, but I want to avoid creating the object that the getter returns every time I am accessing the property. Does anyone have an idea how I can implement that please?
s
you could maybe assign it as a top-level val and then return it as the result of the
get()
Copy code
private val _foo = Foo()

val OtherType.foo: Foo
  get() = _foo
s
thanks @Shawn; that should work; but the object I am trying to create requires another property from the class (or object) on which I am creating the extension
s
if the property this object depends upon is on the instance of a class, then it doesn’t make sense to have a “static” object that depends upon that property
and you’ll have to instantiate a new one of these objects with each instance of the class you’re extending
s
it wouldn’t be idiomatic, but you could keep a private
MutableMap
with the class instance as the key and the property as the value
if the property doesn’t exist for a given instance, create it and store it, otherwise get it from the map
s
maybe I’m misunderstanding the problem, but how would you access the private map from an extension val?
it doesn’t seem like something you’d want to expose with a public getter, even if returned as a
Map
rather than a
MutableMap
but I could be wrong ¯\_(ツ)_/¯
s
Thanks guys @Shawn @serebit. I probably should just move the property to the class instead.
👍 2
s
@Shawn
Copy code
private val map = mutableMapOf<Int>().withDefault { 0 }

val Foo.bar get() = map[this]
s
I don’t think that’ll work since
map
is private within
Foo
oh, I see, as like a separate top-level map
s
yeah