You can easily translate Java code into Kotlin using custom property attributes :
class Example(fooId: Int) { private val fooFuture = supplyAsync { httpClient.get(fooId) } val foo: Foo get() = fooFuture.get() }
But Kotlin has a more powerful concept for generalizing property behavior - property delegates :
class Example { val foo: Foo by someDelegate }
In this example, someDelegate is an object that defines the behavior of the foo property.
Although Future<V> cannot be used as a delegate from a box in Kotlin, you can create your own property delegates by implementing getValue(thisRef, property) and (for mutable properties) setValue(thisRef, property, value) functions, thereby explicitly providing code is executed when a property is read (and written if changed).
These functions can be either member functions for your project classes or extension functions , which is the case with Future<V> . Basically, to use Future<V> as a property delegate, you need to define the extension function getValue(thisRef, value) for it, for example:
operator fun <V> Future<V>.getValue(thisRef: Any?, property: KProperty<*>) = get()
Here, the value that the delegate will provide for the property will simply be taken from a call to Future::get , but the correct implementation should probably take care of undo and exception handling. To this end, you can wrap Future<V> in a class that will also define fallback values ββ/ strategies, and then use the objects of this class in by .
Then you can use Future<V> objects as delegates for your properties:
class Example(fooId: Int) { val foo: Foo by supplyAsync { Thread.sleep(2000); fooId } } fun main(args: Array<String>) { val e = Example(123) println(e.foo) }