在 Scala 中查找自由端口的优雅方法

Cla*_*ion 2 scala

我重新编写了 Java 代码,找到了一个免费端口,我在这里找到了 => https://gist.github.com/vorburger/3429822#file-gistfile1-java以在 Scala 中使用

def findFreePort(): Int = {
    var ss: ServerSocket = null

    try {
      ss = new ServerSocket(0)
      ss.getLocalPort
    } finally {
      ss.close()
    }
  }
Run Code Online (Sandbox Code Playgroud)

然而,将 var 分配给 看起来非常难看null。有更好的方法吗?

Eas*_*sun 5

使用怎么样:

scala> import scala.util.{Using, Try}

scala> def findFreePort(): Try[Int] = Using(new ServerSocket(0)) (_.getLocalPort)
def findFreePort(): util.Try[Int]

scala> findFreePort()
val res1: util.Try[Int] = Success(51865)
Run Code Online (Sandbox Code Playgroud)