Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use with autoclose in Kotlin

Tags:

kotlin

In stdlib/ kotlin.io we find

inline fun <T : Closeable?, R> T.use(block: (T) -> R): R (source)

However it is implemented on Closeable and not on the superinterface AutoCloseable. When working with some frameworks that use AutoCloseable this can be a bit painfull.

Why doesn't Kotlin support "use" with AutoCloseble ?

like image 639
Tomas Karlsson Avatar asked Mar 09 '17 13:03

Tomas Karlsson


People also ask

What does ?: Mean in Kotlin?

In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true , and otherwise evaluates and returns its second operand.

How do I return a value to Kotlin?

To return values, we use the return keyword. In the example, we have two square functions. When a funcion has a body enclosed by curly brackets, it returns a value using the return keyword. The return keyword is not used for functions with expression bodies.

Which function executes the given block function on this resource and then closes it down correctly?

Executes the given block function on this resource and then closes it down correctly whether an exception is thrown or not. In case if the resource is being closed due to an exception occurred in block, and the closing also fails with an exception, the latter is added to the suppressed exceptions of the former.

Is Kotlin different from Java?

Java and Kotlin both are object-oriented programming languages. But both are used for different purposes. Kotlin is used to develop android applications while Java is mainly used for developing enterprise applications.


1 Answers

The kotlin-stdlib is meant for usage with JDK 6 and above, so that it is not aware of AutoCloseable (only added in Java 7).

But you can find the function you need in kotlin-stdlib-jre7, the stdlib extension for JDK 7 added for Kotlin 1.1. You can replace the kotlin-stdlib dependency with it since it depends on the base stdlib itself.

It is defined as:

public inline fun <T : AutoCloseable?, R> T.use(block: (T) -> R): R { ... }

(api reference) (github source)

And it was first mentioned in this blog post.

like image 136
hotkey Avatar answered Sep 27 '22 16:09

hotkey