Getter function


#1

Is there a way to assign a function to a getter? For example:

val stringGetter:()->String = {   "some text" }

val something: String
  get() = stringGetter

This is currently not legal, and I get it, since you’d need to be able to return a function literal. Is there some other way to accomplish this? If not, one possible syntax would be to allow assignment without the brackets:

val something: String   get = stringGetter

Which would distinguish it from the assignment of the string literal as the actual property value.

My specific use case was in trying to implement a generic lazy getter, but I could certainly see other use cases. I wonder if there might also be a use case


#2

Why not just say

``

val something: String
  get() = stringGetter()


?

#3

I'll expand what I was trying to do:

fun <T> lazy(init: ()->T): ()->T {   var _value: Any? = null   var set = false   return {   if (!set) {   _value = init()   set = true   }   _value as T   } }

class PropertiesTest {
  var count = 0

  val something: String   get() = lazy {            count++            "something"   }()

  Test fun prop() {

  val x = something   val y = something   assertEquals(1, count)   }

}
The assertion will fail here, because the outer function is called each time the property is accessed, not the inner function. Is there a way to do this?

#4

Jon, in your example a new object is created for each get invocation. You should keep created object for lazy calculation in separate property. Expanded Andrew suggestion:

class PropertiesTest {   var count = 0   val lazySomething:() -> String = lazy {            count++            "something"   }   val something: String   get() = lazySomething()   test fun prop() {   val x = something   val y = something   assertEquals(1, count)   } }