Kotlin delegates the future

I'm trying to get to know Kotlin, and the delegates are interesting and confused. I have a situation where in the java class I take the arg constructor, create the Future (the identifier represents a resource in another system) and commits the Future as an instange variable. Then "getXXX" will call Future.get()

Here is an example java class

 public class Example { private Future<Foo> foo; public Example(String fooId) { this.foo = supplyAsync(() -> httpClient.get(fooId)); } public Foo getFoo() { return foo.get(); } } 

I am not supplying an example of Kotlin because I am just not sure how to build it.

+5
source share
1 answer

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) } 
+6
source

Source: https://habr.com/ru/post/1258854/


All Articles