简体   繁体   English

从Java代码在Scala Future中包装String

[英]wrapping String in scala Future from java code

I have the following method for testing: 我有以下测试方法:

public scala.concurrent.Future<String> send() { 
  return "OK"; //error - should wrap with future
} 

How can I make it return a scala future (this is java code, so didn't find any example)? 我怎样才能使它返回一个scala的未来(这是java代码,所以没有找到任何例子)?

It's easy if you are working with the Scala 2.12.x library. 如果使用Scala 2.12.x库,这很容易。

In Scala you would write Future(doSomeStuff()) . 在Scala中,您将编写Future(doSomeStuff()) Or simply Future.successful("OK") if you really only want to wrap a literal in a Future . 或者,如果您真的只想将文字包装在Future则可以简单地使用Future.successful("OK") In Java that translates to one of these: 在Java中,可以转换为以下之一:

import scala.concurrent.*;

public Future<String> send1() { 
    return Future.apply( () -> doSomeStuff(), ExecutionContext.global());
}

public Future<String> send2(ExecutionContext ec) { 
    return Future.apply( () -> doSomeStuff(), ec);
}

public Future<String> send3() { 
    return Future.successful("OK");
}

If you have more complex code to run than simply "OK" you'll have to use send1 or send2 . 如果要运行的代码比简单的"OK"要复杂,则必须使用send1send2 Which of those you want depends on whether you want to use the default ExecutionContext or let the caller decide. 您要选择哪一个取决于您要使用默认的ExecutionContext还是让调用者决定。


If your Scala version is lower than 2.12.0, the send1 method from above will look something like this: 如果您的Scala版本低于2.12.0,则上面的send1方法将如下所示:

import scala.concurrent.*;
import scala.runtime.AbstractFunction0;

public Future<String> send1() { 
    return Future$.MODULE$.apply( new AbstractFunction0<String>() {
        public String apply() {
            return doSomeStuff();
        }
    }, ExecutionContext$.MODULE$.global());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM