开发者

How to create an Array from Iterable in Scala 2.7.7?

I'm using Scala 2.7.7

I'm experiencing difficulties with access to the documentation, so code snippets would be greate.

Context

I parse an IP address of 4 or 16 bytes in length. I need an array of bytes, to pass into java.net.InetAddress. The result of String.split(separator).map(_.toByte) returns me an instance of Iterable.

I see two ways to solve the problem

  • use an array of 16 bytes length, fil it from Iterable and return just a part of it, if not all fields are used (Is there a function to fill an array in 2.7.7? How to get the part?).
  • use a dynamic length container and form an 开发者_开发知识库array form it (Which container is suitable?).

Current implementation is published in my other question about memory leaks.


In Scala 2.7, Iterable has a method called copyToArray.


I'd strongly advise you not to use an Array here, unless you have to use a particular library/framework then requires an array.

Normally, you'd be better off with a native Scala type:

String.split(separator).map(_.toByte).toList
//or
String.split(separator).map(_.toByte).toSeq

Update

Assuming that your original string is a delimited list of hostnames, why not just:

val namesStr = "www.sun.com;www.stackoverflow.com;www.scala-tools.com"
val separator = ";"
val addresses = namesStr.split(separator).map(InetAddress.getByName)

That'll give you an iterable of InetAddress instances.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜