frazman
frazman

Reputation: 33293

Casting a list to String in scala

I am playing with scala lately but basically here is what I am trying

  //specify a pattern
  val ptn = "(('[^']*')|([^,]+))".r
  val test = "foo,bar,'foo,bar'"
  pth.findAllmatchIn(test).toArray



 gives Array[scala.util.matching.Regex.Match] = Array(foo and bar, bar and foo, 'foo, is bar')

What I was hoping for was Array[String] in return? But I dont want an extra loop to do typecasting. Since I am new in scala, I was wondering if there is some other way to get the results of regex as string? Thanks

Upvotes: 0

Views: 408

Answers (3)

toto2
toto2

Reputation: 5326

ptn.findAllMatchIn(test).map(_.toString)

does the trick. As you said, you don't want an extra loop, and in Scala you can usually do most things without (explicit) loops.

Also, in Scala you usually want to stick with List instead of arrays: .toList instead of .toArray.

Upvotes: 1

Randall Schulz
Randall Schulz

Reputation: 26486

You flatly cannot "cast" a List to a String.

It's important to understand the difference between casting and conversion.

Conversion is an arbitrary computation that produces one value from another with no required relationship between the original and converted values' types.

Casting is asserting a different static type for some value, which succeeds only when the asserted type is really one of the types of the value being cast. Casting "upward" (to a wider type) always succeeds while casting to a narrower type can fail. So casting a String to Object will always succeed while casting a String to, say, a List will always fail. In fact, no other cast (other than Scala's faux type AnyRef) will succeed, since String is a final class and thus has no sub-types.

Upvotes: 2

Chirlo
Chirlo

Reputation: 6130

You can make it in one step with findAllIn, which returns an iterator that you can force to a List.

ptn.findAllIn(test).toList

Upvotes: 1

Related Questions