我正在尝试使用 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/