Basilevs
Basilevs

Reputation: 23916

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

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

Upvotes: 1

Views: 5345

Answers (2)

Kevin Wright
Kevin Wright

Reputation: 49705

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.

Upvotes: 1

user382157
user382157

Reputation:

In Scala 2.7, Iterable has a method called copyToArray.

Upvotes: 2

Related Questions