Seq view with only one item?

Often I find myself passing in Seq

only one element for methods like this:

def myMethod(myList: Seq[Int]) = { ... }

      

I usually do it like this:

myMethod(List(42))

      

But it seems to me that this might not be the most elegant way, and if there is one thing about Scala that I love, it is its ability to choke my mind by shortening the symbols used when I thought it was impossible.

So, is there a shorter or more elegant representation of a single element Seq

than List(42)

?

I can imagine a couple of worse options!

42 to 42
42 :: List()

      

+3


source to share


2 answers


Probably the shortest built-in way is to use the Seq

applicable companion object and write

myMethod(Seq(42))

      

This applicable function returns the standard implementation Seq

, i.e. A, List

and is therefore equivalent to use List(42)

.



I'm not sure if there is an implementation Seq

with a shorter name, but you can confidently implement your own, or just import Seq

(or List

) when overlaying the name:

scala> import scala.collection.{Seq => S}

scala> S(42)
res0: Seq[Int] = List(3)

      

+3


source


Shorter usage syntax can be obtained with this implicit,

implicit def SingletonSeq(i: Int) = Seq(i)

      



Hence,

def myMethod(myList: Seq[Int]) = myList.size

myMethod(42)
res: 1

      

+1


source







All Articles