Scala Basics - A Guide to Using Underscores

The underscore symbol runs through almost any Scala programming book, and has different meanings in different scenarios, confusing many beginners. Because of this, the underscore is a special symbol that increases the difficulty of getting started with Scala. This article hopes to help beginners level this hill.

1. The equivalent syntax used to replace Java

Since most Java keywords have new meanings in Scala, some basic syntax has changed slightly in Scala.

1.1 Import wildcards

It is a legal method name in Scala, so use _ instead when importing a package.

// Java 
import java.util. * ;

// Scala 
import java.util._

1.2 Class member default values

Class members in Java can not be assigned an initial value, the compiler will automatically set a suitable initial value for you:

class Foo{
      // Default value of String type is null 
     String s;
}

In Scala, it must be specified explicitly. If you are lazy, you can use _ to let the compiler automatically set the initial value for you:

class Foo{
     // Default value of String type is null 
    var s: String = _
}

Note: This syntax only applies to class members, not local variables.

1.3 Variable parameters

Java declares variadic parameters as follows:

public static void printArgs(String ... args){
    for(Object elem: args){
        System.out.println(elem + " ");
    }
}
The calling method is as follows:
 // Pass in two parameters 
printArgs( " a " , " b " );
 // You can also pass in an array 
printArgs( new String[]{ " a " , " b " });

In Java, you can pass an array directly to the printArgs method, but in Scala, you have to explicitly tell the compiler whether you want to pass the collection as a separate parameter, or the elements of the collection. In the latter case, use the underscore:

printArgs(List("a", "b"): _*)

1.4 Type wildcards

Java's generic system has a wildcard type, such as List<?>. Any List<T> type is a subtype of List<?>. If we want to write a method that can print all elements of the List type, we can declare it as follows :

public static void printList(List<?> list){
    for(Object elem: list){
        System.out.println(elem + " ");
    }
}

The corresponding Scala version is:

def printList(list: List[_]): Unit ={
   list.foreach(elem => println(elem + " "))
}

2 pattern matching

2.1 Default matching

str match{
    case "1" => println("match 1")
    case _   => println("match default")
}

2.2 Matching set elements

// match a list of length three starting with 0 
expr match {
   case List( 0 , _, _) => println( " found it " )
   case _ =>
}

// match any list starting with 0 and any length 
expr match {
   case List( 0 , _*) => println( " found it " )
   case _ =>
}

// match tuple elements 
expr match {
   case ( 0 , _) => println( " found it " )
   case _ =>
}

// Assign the first element to the head variable 
val List(head, _*) = List( " a " )

3. Scala-specific syntax

3.1 Accessing Tuple elements

val t = (1, 2, 3)
println(t._1, t._2, t._3)

3.2 Shorthand function literal (function literal)

If a function's parameter appears only once within the function body, an underscore can be used instead:

val f1 = (_: Int) + (_: Int)
 // equivalent to 
val f2 = (x: Int, y: Int) => x + y

list.foreach (println(_))
 // equivalent to 
list.foreach ( e => println (e))

list.filter(_ > 0 )
 // equivalent to 
list.filter(x => x > 0 )

3.3 Defining unary operators

In Scala, operators are actually methods. For example, 1 + 1 is equivalent to 1.+(1). Using underscores, we can define our own left-placement operators. For example, negative numbers in Scala are implemented with left-placement operators:

- 2 
// equivalent to 
2 .unary_-

3.4 Defining assignment operators

We implement the assignment operator with underscore, which allows precise control over the assignment process:

class Foo {
      def name = { "foo" }
      def name_=(str: String) {
        println("set name " + str)
   }

    val m = new Foo()
    m.name = " Foo "  // equivalent to: m.name_=("Foo")

3.5 Defining a partially applied function

We can call a function with only some parameters, and the returned result is a new function, that is, a partially applied function. Partially applied functions get their name because only some of the arguments are provided.

def sum(a: Int, b: Int, c: Int) = a + b + c
val b = sum(1, _: Int, 3)
b: Int => Int = <function1>
b(2) //6

3.6 Converting methods to functions

Methods and functions in Scala are two different concepts. Methods cannot be passed as parameters or assigned to variables, but functions can. In Scala, methods can be converted to functions using underscores:

// Convert the println method to a function and assign it to p 
val p = println _  
 // p: (Any) => Unit

4. Summary

Underscores appear in the form of syntactic sugar in most application scenarios, which can reduce the number of keystrokes and make the code more concise. However, it is a little difficult for students who are not familiar with underscores to read. I hope this article can help you solve this confusion.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324738795&siteId=291194637