调用java.util.ArrayList.toArray方法时scala参数类型不兼容错误

时间:2015-12-29 10:03:51

标签: scala type-mismatch

我试图将async communication java sample code(Redis客户端之一)的Lettuce转换为scala,但遇到编译错误,说参数表达式的类型不兼容。

这是我的代码

  def RunAsync() = {
    val redisClient = new RedisClient(RedisURI.create(connURL))
    val connection = redisClient.connectAsync()

    connection.setAutoFlushCommands(false)

    val futures = Lists.newArrayList[RedisFuture[_]]()

    for(lc <- Range(0, logCount))
    {
      futures.add(connection.set(logContents(lc).key, logContents(lc).value))
    }

    connection.flushCommands()

    val convFutures = futures.toArray(new Array[RedisFuture[_]](futures.size()))
    val result = LettuceFutures.awaitAll(10L, TimeUnit.SECONDS, convFutures : _*)

    connection.close()
    redisClient.shutdown()
  }

这是我在编译期间收到的错误信息

Error:(67, 31) no type parameters for method toArray: (x$1: Array[T with Object])Array[T with Object] exist so that it can be applied to arguments (Array[com.lambdaworks.redis.RedisFuture[_]])
              --- because ---
              argument expression's type is not compatible with formal parameter type;
              found   : Array[com.lambdaworks.redis.RedisFuture[_]]
              required: Array[?T with Object]
              Note: com.lambdaworks.redis.RedisFuture[_] >: ?T with Object, but class Array is invariant in type T.
              You may wish to investigate a wildcard type such as `_ >: ?T with Object`. (SLS 3.2.10)
                 val convFutures = futures.toArray(new Array[RedisFuture[_]](futures.size()))
                                   ^

经过几个小时的谷歌搜索,我可以找到一些参考资料来帮助了解我的情况,但未能找到解决方案。有人可以指导我解决这个问题的最佳方法吗?

1 个答案:

答案 0 :(得分:1)

为什么使用java列表?试试这个:

val convFutures = Range(0, logCount).map { lc => 
   connection.set(logContents(lc).key, logContents(ls).value))
}.toArray

什么类型logContents btw?可能会让它更简单...

此外,看起来你根本不需要.toArray。 scala中的Varargs param为Seq,而不是Array

相关问题