3

In Perl I can do

my @l = qw( str1 str2 str3 str4 )

And in Ruby

l = %w{ str1 str2 str3 str4 }

But in Scala it looks like I'm stuck with

val l = List( "str1", "str2", "str3", "str4" )

Do I really need all those "s and ,s?

3
  • 2
    So how do Perl and Ruby deal with whitespace in str1 for example? Commented Jan 31, 2013 at 19:19
  • 1
    0__ in perl, "qw" means quote word and splits on white space. For strings with spaces qw is not appropriate, the initialisation would in that case be just like scala Commented Jan 31, 2013 at 19:24
  • Yes, what @Vorsprung said. It doesn't cover all cases, but an useful subset. Commented Jan 31, 2013 at 19:48

1 Answer 1

16

You could do

implicit class StringList(val sc: StringContext) extends AnyVal {
  def qw(): List[String] = 
    sc.parts.flatMap(_.split(' '))(collection.breakOut)
}

qw"str1 str2 str3"

Or via implicit class:

implicit class StringList(val s: String) extends AnyVal {
  def qw: List[String] = s.split(' ').toList
}

"str1 str2 str3".qw

(Both require Scala 2.10, although the second one can be adapted for Scala 2.9)

Sign up to request clarification or add additional context in comments.

4 Comments

Clever use of the new string interpolation factility. It (the first one) is Scala 2.10 only, though.
Actually, I'd split the parts, but interpolate args in their original places, without splitting them.
You must not put arguments to the method. def qw() = ... is enough.
@sschaef - ah, didn't know. i have edited the answer accordingly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.