【问题标题】:how to use try-resources in kotlin?如何在 kotlin 中使用 try-resources?
【发布时间】:2018-10-31 05:01:42
【问题描述】:

我正在尝试使用 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 inline fun ???.use(block: (???) -> ???): ???在 kotlin.io 中定义

【问题讨论】:

    标签: java kotlin try-catch


    【解决方案1】:

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

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

    替换为:

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

    【讨论】:

      猜你喜欢
      • 2016-06-03
      • 1970-01-01
      • 2015-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多