使用Scala trait作为回调接口

时间:2016-07-10 06:43:45

标签: scala traits

我刚刚开始学习scala并尝试通过制作一个简单的应用程序来学习自己,dicebot。

这是处理这个简单命令的简单应用程序。

  

CommandRouter()。run(“dice roll 3d4”)

interface KwoolyHttpCallback {
    void onWeatherJsonDataReceived(String result);
    void onWeatherBitmapDataReceived(Bitmap result);
}

private void initializeKwoolyHttpCallbackFunction() {
httpClientCallback = new KwoolyHttpCallback() {
    @Override
    public void onWeatherJsonDataReceived(String result) {
       try {
            dataModel.setWeatherJsonData(result);
            queryWeatherBitmapData();   
       } catch (Exception e) {
            Log.e(getClass().getName(), "Exception: ");
            e.printStackTrace();
       }
   }

顺便说一下,在应用程序的第一部分,我想传递一个回调函数,当Dice Bot完成它的工作时会调用它。

  

Dice.run(_command.tail,回调

事情是..我不太确定要为回调参数传递什么。 如果这是Java,我将定义一个如下所示的接口,但在scala中,我不确定要使用什么。

trait BotInterface {
  def onReceiveResult(result: List[String]): List[String]
}

我从某个地方听说这个特性是界面,但我真的没有得到它。

{{1}}

你能教我如何使用这个特性作为回调界面吗?

提前致谢! :)

1 个答案:

答案 0 :(得分:1)

如果您需要的是回调,需要List[String]并返回List[String],那么就不需要特征,您可以要求功能

def run(command: List[String], callback: List[String] => List[String]): List[String]

callback使用一点语法糖来定义。它实际上被转换为名为Function1[List[String], List[String]]的类型。

现在调用者可以使用匿名函数语法来传递实现:

run(List("1","2","3"), l => { 
  l.foreach(println)
  l
})

我们甚至可以通过使用第二个参数列表(这称为currying)使这更漂亮:

def run(command: List[String])(callback: List[String] => List[String]): List[String]

现在我们有:

run(List("1","2","3")) { l =>
  l.foreach(println)
  l
}

如果您仍然确信自己想要trait,那么它实际上与您在Java中定义界面的方式非常相似:

trait BotInterface {
  def onReceiveResult(result: List[String]): List[String]
}

def run(command: List[String], callback: BotInterface): List[String]

请注意,Scala中的traits可以具有默认实现,类似于Java 8的默认方法:

trait BotInterface {
  def onReceiveResult(result: List[String]): List[String] = result.map(_.toLowerCase)
}

run定义中,您需要致电callback.onReceiveResult(list)

相关问题