如何在Kotlin中使用try-resources?

时间:2018-10-31 05:01:43

标签: java kotlin try-catch

我正在尝试使用kotlin而不是Java,但找不到与try资源相关的好方法:

这样的Java代码:

import org.tensorflow.Graph;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
import org.tensorflow.TensorFlow;

public class HelloTensorFlow {
  public static void main(String[] args) throws Exception {
    try (Graph g = new Graph()) {
      final String value = "Hello from " + TensorFlow.version();

      // Construct the computation graph with a single operation, a constant
      // named "MyConst" with a value "value".
      try (Tensor t = Tensor.create(value.getBytes("UTF-8"))) {
        // The Java API doesn't yet include convenience functions for adding operations.
        g.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build();
      }

      // Execute the "MyConst" operation in a Session.
      try (Session s = new Session(g);
          // Generally, there may be multiple output tensors,
          // all of them must be closed to prevent resource leaks.
          Tensor output = s.runner().fetch("MyConst").run().get(0)) {
        System.out.println(new String(output.bytesValue(), "UTF-8"));
      }
    }
  }
}

我在Kotlin中这样做,我必须这样做:

fun main(args: Array<String>) {
    val g = Graph();
    try {
        val value = "Hello from ${TensorFlow.version()}"
        val t = Tensor.create(value.toByteArray(Charsets.UTF_8))
        try {
            g.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build()
        } finally {
            t.close()
        }

        var sess = Session(g)
        try {
            val output = sess.runner().fetch("MyConst").run().get(0)
            println(String(output.bytesValue(), Charsets.UTF_8))
        } finally {
            sess?.close()
        }
    } finally {
        g.close()
    }

}

我尝试像这样使用use

Graph().use {
    it -> ....
}

我遇到这样的错误:

Error:(16, 20) Kotlin: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: 

@InlineOnly仅公开内联乐趣???。use(block:(???)-> ???):???在kotlin.io中定义

1 个答案:

答案 0 :(得分:0)

我只是使用了错误的依赖项:

 compile "org.jetbrains.kotlin:kotlin-stdlib"

替换为:

compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8"