如何在intellij中使用scala.collection.JavaConverters?

时间:2019-06-24 02:24:03

标签: scala intellij-idea

我想在scala中使用java nio,我尝试将此代码转换为scala:

ServerSocketChannel ssChannel = ServerSocketChannel.open();
int port = 9001;
ssChannel.bind(new InetSocketAddress(port));
Selector selector = Selector.open();

ssChannel.configureBlocking(false);
ssChannel.register(selector, SelectionKey.OP_ACCEPT); 

while (true) {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
for (SelectionKey key : keys) {
  if (key.isAcceptable()) { 
    ServerSocketChannel ssc = (ServerSocketChannel) key
    .channel();
    SocketChannel sc = ssc.accept();
    sc.configureBlocking(false);
    sc.register(selector, SelectionKey.OP_READ); 
  }
  if(key.isReadable()){ 
    SocketChannel sc = (SocketChannel) key.channel();
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    sc.read(buffer);

    buffer.flip();
    sc.write(buffer);
  }
}
keys.clear();
}
}

当我将此代码复制到intellij时,intellij问我是否要将此代码转换为scala,我同意。

然后是Intellij

import scala.collection.JavaConversions._,

告诉我一个红色错误

我在intellij中使用scala 2.12.7,我检查了scala api文档,JavaConversion已弃用,所以我

import scala.collection.JavaConverters._

但是intellij告诉我它已被弃用,让我使用

scala.jdk.CollectionConverters

当我导入它时,该行中仍然存在错误:

key.isAcceptable

那么如何在intellij中转换此代码?谢谢!

我的intellij版本是2018.3.4 Community Edition

1 个答案:

答案 0 :(得分:0)

这是Java代码的非常天真,逐行的翻译。

我不知道它是否可以满足您的要求,我在相当长的一段时间内没有做太多的NIO或涉足Java领域,但是它确实可以编译。

import java.nio.channels.{ServerSocketChannel,Selector,SelectionKey,SocketChannel}
import java.net.InetSocketAddress
import java.nio.ByteBuffer
import collection.JavaConverters._

val ssChannel :ServerSocketChannel = ServerSocketChannel.open()
val port = 9001
ssChannel.bind(new InetSocketAddress(port))
val selector :Selector = Selector.open()

ssChannel.configureBlocking(false)
ssChannel.register(selector, SelectionKey.OP_ACCEPT)

while (true) {
  selector.select()
  val keys :collection.mutable.Set[SelectionKey] = selector.selectedKeys().asScala
  for (key <- keys) {
    if (key.isAcceptable()) {
      val ssc :ServerSocketChannel = key.channel().asInstanceOf[ServerSocketChannel]
      val sc :SocketChannel = ssc.accept()
      sc.configureBlocking(false)
      sc.register(selector, SelectionKey.OP_READ)
    }
    if(key.isReadable()){
      val sc :SocketChannel = key.channel().asInstanceOf[SocketChannel]
      val buffer :ByteBuffer = ByteBuffer.allocate(1024)
      sc.read(buffer)
      buffer.flip()
      sc.write(buffer)
    }
  }
  keys.clear()
}

您会注意到,在此示例中,JavaConverters仅用于从Java mutable.Set获取Scala Set,而仅用于制作{{ 1}}(理解力内部)。