java - 如何在 kotlin 中使用 try-resources?

标签 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 公共(public)内联乐趣 ???.use(block: (???) -> ???): ???在 kotlin.io 中定义

最佳答案

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

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

将其替换为:

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

关于java - 如何在 kotlin 中使用 try-resources?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53076595/

相关文章:

node.js - Node and sequelize -> .catch(...) 没有按预期工作

java - 如何使用 JAXP DocumentBuilder 提供自定义错误消息?

java - 为 SauceLabs 执行设置 DesiredCapability 时出错

java - OSX 上使用 javax.sound.midi 的 Midi 设备

android - Android产品Gradle-kotlin-dsl中的香料

kotlin - 抑制 Intellij 中公共(public) API 函数的 "unused"警告(对于 Kotlin)

java - Android Studio Gradle 同步失败 : Unable to start the daemon process

java - 无法加载admob广告错误:3 ERROR_CODE_NO_FILL

c# - 错误和异常处理

ios - Objective-C try-catch - 为什么编译?为什么返回不同的构建调试与发布?