I've taken a look at the list of surveys taken on scala-lang.org and noticed a curious question: "Can you name all the uses of “_”?". Can you? If yes, please do so here. Explanatory examples are appreciated.
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 .
Scala some class returns some value if the object is not null, it is the child class of option. Basically, the option is a data structure which means it can return some value or None. The option has two cases with it, None and Some.
Scala functions are first class values. Difference between Scala Functions & Methods: Function is a object which can be stored in a variable. But a method always belongs to a class which has a name, signature bytecode etc. Basically, you can say a method is a function which is a member of some object.
The ones I can think of are
def foo(l: List[Option[_]]) = ...
case class A[K[_],T](a: K[T])
val _ = 5
List(1, 2, 3) foreach { _ => println("Hi") }
trait MySeq { _: Seq[_] => }
Some(5) match { case Some(_) => println("Yes") }
"abc" match { case s"a$_c" => }
C(1, 2, 3) match { case C(vs @ _*) => vs.foreach(f(_)) }
import java.util._
import java.util.{ArrayList => _, _}
def bang_!(x: Int) = 5
def foo_=(x: Int) { ... }
List(1, 2, 3) map (_ + 2)
List(1, 2, 3) foreach println _
def toFunction(callByName: => Int): () => Int = callByName _
var x: String = _ // unloved syntax may be eliminated
There may be others I have forgotten!
Example showing why foo(_)
and foo _
are different:
This example comes from 0__:
trait PlaceholderExample { def process[A](f: A => Unit) val set: Set[_ => Unit] set.foreach(process _) // Error set.foreach(process(_)) // No Error }
In the first case, process _
represents a method; Scala takes the polymorphic method and attempts to make it monomorphic by filling in the type parameter, but realizes that there is no type that can be filled in for A
that will give the type (_ => Unit) => ?
(Existential _
is not a type).
In the second case, process(_)
is a lambda; when writing a lambda with no explicit argument type, Scala infers the type from the argument that foreach
expects, and _ => Unit
is a type (whereas just plain _
isn't), so it can be substituted and inferred.
This may well be the trickiest gotcha in Scala I have ever encountered.
Note that this example compiles in 2.13. Ignore it like it was assigned to underscore.
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