神奇的_scala

刚开始学习scala,就被它的难住了。下面我们看看scala中的用法

1. 模式匹配

在scala中,模式匹配有点类似于java中的switch语句。

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

scala中, 是按顺序匹配的, 先匹配的先执行, 上面例子中的就是一个通配符,它会匹配所有的字符。scala还允许嵌套模式。我们来看看 嵌套的例子

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 _ =>
  }

TODO: test not working.

2.匿名函数

scala中定义匿名函数非常优雅,_在语法中表示一个占位符。

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

等价于如下语法, _表示参数

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

我们再举一个两个参数的例子

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

3.import

在导入包时,_的作用和java中的*是一样的。

// 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 => _ , _ }

4.properties

在scala中, 一个对象可以隐式定义非私有变量, getter和变量名相同,_=和setter相当

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)

5.函数

scala是一种函数语言,我们可以把函数当做普通的变量,如果你给变量赋值为一个函数,那么会调用函数,并将结果赋值给这个变量。我们应该在函数后加上 _ 调用函数给变量赋值, 减少括号的混淆。

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

6.参考

http://ananthakumaran.in/2010/03/29/scala-underscore-magic.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值