您的位置:首页 > 其它

scala中下划线(undercore)

2016-05-02 08:22 585 查看
scala undercore(下划线)是怎么回事?

class sheet1 {
var c:String =_
通过jd编译,得到如下

public class sheet1
{
private String c;

public String c()
{
return this.c; }
public void c_$eq(String x$1) { this.c = x$1;
}
}

发现下划线(_)在实际编译 位置中是x$1,x$1是形式参数,下划线就相当于一个匿名的实参,在這里占了一个位置给别人,当再次赋值的时候,就会改变实际值,也就是说“_”是用来过度的,第一个:1、默认初始化(val def不行)

就是这个匿名实参的初始值。

note:
$后面跟数字是匿名类编译出来的
$后面跟文字是内部类编译出来的


下面就来看看scala中下划线的作用

1、默认初始化(val def不行)

var a:Int =_
//a: Int = 0
var b:Double =_
//b: Double = 0.0
var c:String =_
c: String = null
var d:List[Int]=_
//d: List[Int] = null


2、Existential types(存在性类型)

def foo(l: List[Option[_]]) = ...
3、Higher kinded type parameters(高阶类型参数)

case class A[K[_],T](a: K[T])


4、Ignored variables(临时变量)

val _ = 5
val (a,_) = (5,2)</span>



5、Ignored parameters(临时参数)

List(1, 2, 3) foreach { _ => println("Hi") }
6、Wildcard patterns(通配模式)

Some(5) match { case Some(_) => println("Yes") }


7、Wildcard imports(通配导入)

import java.util._


8、Hiding imports(隐藏导入)

import java.util.{ArrayList => _, _}


9、Joining letters to punctuation(把字幕连接到标点符号)
def bang_!(x: Int) = 5

10、Assignment operators(分配算子)

def foo_=(x: Int) { ... }


11、Placeholder syntax(占位符语法)

List(1, 2, 3) map (_ + 2)


12、Partially applied functions(偏函数功能)

List(1, 2, 3) foreach println _
13、parameters Sequence(参数序列)

//_*作为一个整体,告诉编译器你希望将某个参数当作参数序列处理。例如val s = sum(1 to 5:_*)就是将1 to 5当作参数序列处理。
//Range转换为List
List(1 to 5:_*)

//Range转换为Vector
Vector(1 to 5: _*)

//可变参数中
def capitalizeAll(args: String*) = {
args.map { arg =>
arg.capitalize
}
}
val arr = Array("what's", "up", "doc?")
capitalizeAll(arr: _*)
Example showing why foo(_) and foo _ are different:

foo _ // Eta expansion of method into method value

foo(_) // Partial function application

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.

可以总结出这个一条规律:下划线和之前的那个东东挨在一起(中间没空),那么就是前面那个东东的参数,

如果中间有空格,那么就是前面那个东东的方法

参考文献
http://stackoverflow.com/questions/8000903/what-are-all-the-uses-of-an-underscore-in-scala
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: