tags:

views:

54

answers:

2

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.

+2  A: 

In Scala 2.7, Iterable has a method called copyToArray.

MJP
How do I truncate array then, to return only used cells?
Basilevs
A: 

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.

Kevin Wright
java.net.InetAddress.getByAddress(byte[] addr) requires Byte Array
Basilevs
getByName fails on dns errors
Basilevs