Unary operator for parameter-less get

So I read your response mostly as “I don’t like your solution because I can’t hit it with my hammer, which is the only tool I have and know how to use”

X is just a property here just for simplifying the illustration by giving a name to the value. it is just a value and could be inlined in the example. So lets do that using my revised code that got rid of the delegate:

private val readCounter = AtomicInteger()

val cont = "The value you are trying to expose through cont property"
    get() = field.apply{readCounter.getAndIncrement()}

I could actually get rid of the backing field on cont and put the value into the getter, but then I would have had to specify the type for cont in the example

You have to store the state of the count somewhere so that can’t be eliminated it will be a property somewhere. The only real question here is how someone reads the count of accesses. I was assuming that the object that declared the cont property was the only one that needed the count so I stored it there. Feel free to move it somewhere else.

To me the question is how do you get count of accesses of the property. Is it an attribute of the property or is it separate from the property. If the latter then I already showed the solution for that. If the former then you have to a way to say you want the access count for the property or you want the value of the property. In that case you need to quit thinking of the property as thing that has a value, but instead it should be viewed as a function that produces a value, Don’t think of it as an object that you call get on, it is a function you can invoke to get a result. So this would be the appropriate solution:

class CountedFunction<T>(private val producer: () -> T) : () -> T
{
    constructor(value: T) : this( { value } )

    val counter = AtomicInteger()

    val invocationCount: Int get() = counter.get()

    override fun invoke() = producer().apply { counter.getAndIncrement() }
}

val cont = CountedFunction("value to return")

fun foo()
{
    val x = cont();
    println("cont was invoked ${cont.invocationCount} times")
}

I realize this is not the way you normally think about it since you probably are not use to functional programming.

#ref carries no meaning and makes me think someone is trying to write Perl. I have no objections to having the operator overloading allowing a no parameter version of get to allow ref although I don’t think this is an intuitive use of .

Once again, what is a WeakReference in a functional programming mindset, it is a function that you can invoke to get the value (or null). So the solution is

inline operator fun <T> WeakReference<T>.invoke() = get()

Then I can use function call semantics on any WeakReference as in

val x = someWeakReference() // Result will be nullable

Good luck convincing anyone that #ref is a better choice than ref()

No idea what you were trying to say here