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?
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.
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.
=> 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 .
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 .
_._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.
_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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With