theglauber
theglauber

Reputation: 29615

Is there a convenient way to initialize a list of strings in Scala?

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?

Upvotes: 3

Views: 810

Answers (1)

0__
0__

Reputation: 67280

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)

Upvotes: 16

Related Questions