I started learning Scala a few days before. Initially i was annoyed by the use of too many symbols in Scala. Especially i was confused by the _ and its different meaning in different places. After a few days of research(aka search), i felt better and i started to love its syntax. Ok, lets see the usage of _ in Scala.

"Alert" : "I am a Scala n00b"

Pattern Matching

In Scala, pattern matching is somewhat similar to java switch statement. But it is more powerful.

def matchTest(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "anything other than one and two"
}

In Scala, each selector will be matched with the patterns in the order they appear and the first match will be executed. _ acts like a wildcard. It will match anything. Scala allows nested patterns, so we can nest the _ also.Lets see another example that uses _ in nested pattern.

expr match {
case List(1,_,_) => " a list with three element and the first element is 1"
case List(_*) => " a list with zero or more elements "
case Map[_,_] => " matches a map with any key type and any value type "
case _ =>
}

Anonymous Functions

Scala represents anonymous functions with a elegant syntax. The _ acts as a placeholder for parameters in the anonymous function. The _ should be used only once, But we can use two or more underscores to refer different parameters.

List(1,2,3,4,5).foreach(print(_))
List(1,2,3,4,5).foreach( a => print(a))

Here the _ refers to the parameter. The first one is a short form of the second one. Lets look at another example which take two parameters.

val sum = List(1,2,3,4,5).reduceLeft(_+_)
val sum = List(1,2,3,4,5).reduceLeft((a, b) => a + b)

There is a good post which explains the inner details of the above example.

import

In scala, _ acts similar to * in java while importing packages.

// imports all the classes in the package matching
import scala.util.matching._
// imports all the members of the object Fun. (static import in java)
import com.test.Fun._
// imports all the members of the object Fun but renames Foo to Bar
import com.test.Fun.{ Foo => Bar , _ }
// imports all the members except Foo. To exclude a member rename it to _
import com.test.Fun.{ Foo => _ , _ }

Properties

In scala, a getter and setter will be implicitly defined for all non-private var in a object. The getter name is same as the variable name and _= is added for setter name. We can define our own getters and setters. This is looking similar to Ruby getters and setters. Ok lets see an example which uses the getter and setters.

class Test {
private var a = 0
def age = a
def age_=(n:Int) = {
require(n>0)
a = n
}
}
val t = new Test
t.age = 5
println(t.age)

Functions

Scala is a functional language. So we can treat function as a normal variable. If you try to assign a function to a new variable, the function will be invoked and the result will be assigned to the variable. This confusion occurs due to the optional braces for method invocation. We should use _ after the function name to assign it to another variable.

class Test {
def fun = {
// some code
}
val funLike = fun _
}

Scala _ [underscore] magic的更多相关文章

  1. scala _ parameter

    Given that sequence, use reduceLeft to determine different properties about the collection. The foll ...

  2. WPF中的CheckBox的_ (underscore / 下划线)丢失

    今天在项目中遇到check box的Content的内容缺少'_', 原因是WPF的ContentPresenter默认会把'_'作为加速键的转义字符.  比方CheckBox的content为&qu ...

  3. Scala _ 下划线

    1.引入包中的全部方法 import math._ //引入包中所有方法,与java中的*类似 2.表示集合元素 val a = (1 to 10).filter(_%2==0).map(_*2) / ...

  4. Scala underscore的用途

    _ 的用途 // import all import scala.io._ // import all, but hide Codec import scala.io.{Codec => _, ...

  5. Beginning Scala study note(9) Scala and Java Interoperability

    1. Translating Java Classes to Scala Classes Example 1: # a class declaration in Java public class B ...

  6. Scala详解

    1       快速入门... 4 1.1             分号... 4 1.2             常变量声明... 4 1.2.1         val常量... 4 1.2.2  ...

  7. Scala基础语法 (一)

    如果你之前是一名 Java 程序员,并了解 Java 语言的基础知识,那么你能很快学会 Scala 的基础语法. Scala 与 Java 的最大区别是:Scala 语句末尾的分号 ; 是可选的. 我 ...

  8. Scala HandBook

    目录[-] 1.   Scala有多cool 1.1.     速度! 1.2.     易用的数据结构 1.3.     OOP+FP 1.4.     动态+静态 1.5.     DSL 1.6 ...

  9. Scala包

    #引入包的全部成员的办法 import scala.collection._ #引入同一个包中的几个成员 import scala.collection.{A,B} #重名 要 重命名 import ...

随机推荐

  1. 【转】MySQL中增加sequence管理功能(模拟创建sequence)

    1.oracel可以直接支持sequence,但是mysql不支持sequence,因此我们要通过模拟sequence的方法在mysql中创建sequence.模拟sequence的方法:项目场景:项 ...

  2. TestPointer

     C++ Code  12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 ...

  3. 【JAVA、C++】 LeetCode 008 String to Integer (atoi)

    Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...

  4. mongodb数据结构学习1--增删改查

    插入文档 在数据库中,数据插入是最基本的操作,在MongoDB使用db.collection.insert(document)语句来插入文档: document是文档数据,collection是存放文 ...

  5. Balance(poj 1837)

    题意:一个天平上有C个挂钩,第i个挂钩的位置为C[i],C[i] < 0表示该挂钩在原点的左边,C[i] > 0表示该挂钩在原点的右边:然后给出G个钩码的重量,问有多少种挂法使得天平保持平 ...

  6. 数据库优化和SQL操作的相关题目

    SQL操作 1.有一个数据库表peope,表有字段name,age,address三个属性(注:没有主键).现在如果表中有重复的数据,请删去重复只留下其中的一条.重复的定义就是两条记录的name,ag ...

  7. Ubuntu配置java环境变量

    参考文章: http://www.cnblogs.com/BigIdiot/archive/2012/03/26/2417547.html 方法1:修改/etc/profile 文件所有用户的 she ...

  8. .net学习之类与对象、new关键字、构造函数、常量和只读变量、枚举、结构、垃圾回收、静态成员、静态类等

    1.类与对象的关系类是对一类事务的统称,是抽象的,不能拿来直接使用,比如汽车,没有具体指哪一辆汽车对象是一个具体存在的,看的见,摸得着的,可以拿来直接使用,比如我家的那辆刚刚买的新汽车,就是具体的对象 ...

  9. SQL语句优化原则

    处理百万级以上的数据提高查询速度的方法: .应尽量避免在 .对查询进行优化,应尽量避免全表扫描,首先应考虑在 .应尽量避免在   .应尽量避免在  or num=      可以这样查询:       ...

  10. LightOJ 1248 Dice (III) 概率

    Description Given a dice with n sides, you have to find the expected number of times you have to thr ...