Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do _._1 and _++_ mean in Scala (two separate operations)?

Tags:

scala

My interpretation of _._1 is:

_ = wildcard parameter _1 = first parameter in method parameter list But when used together with . what does it signify?

This is how its used :

.toList.sortWith(_._1 < _._1)

For this statement:

_++_

I'm lost. Is it concatenation two wildcard parameters somehow? This is how its used:

.reduce(_++_)

I would be particularly interested if they above code could be made more verbose and remove any implicits, just so I can understand it better?

like image 704
user701254 Avatar asked Oct 24 '12 09:10

user701254


People also ask

What is the use of tuple in Scala?

In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are immutable. Tuples are especially handy for returning multiple values from a method.

Why is _ used in Scala?

Scala allows the use of underscores (denoted as '_') to be used as placeholders for one or more parameters. we can consider the underscore to something that needs to be filled in with a value. However, each parameter must appear only one time within the function literal.

What is the meaning of => in Scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .

What does case _ mean in Scala?

case _ => does not check for the type, so it would match anything (similar to default in Java). case _ : ByteType matches only an instance of ByteType . It is the same like case x : ByteType , just without binding the casted matched object to a name x .


2 Answers

_._1 calls the method _1 on the wildcard parameter _, which gets the first element of a tuple. Thus, sortWith(_._1 < _._1) sorts the list of tuple by their first element.

_++_ calls the method ++ on the first wildcard parameter with the second parameter as an argument. ++ does concatenation for sequences. Thus .reduce(_++_) concatenates a list of sequences together. Usually you can use flatten for that.

like image 185
Kim Stebel Avatar answered Sep 19 '22 08:09

Kim Stebel


_1 is a method name. Specifically tuples have a method named _1, which returns the first element of the tuple. So _._1 < _._1 means "call the _1 method on both arguments and check whether the first is less than the second".

And yes, _++_ concatenates both arguments (assuming the first argument has a ++ method that performs concatenation).

like image 33
sepp2k Avatar answered Sep 22 '22 08:09

sepp2k