scala _的用法
来源:互联网 发布:coc武神升级数据 编辑:程序博客网 时间:2024/04/30 19:14
The ones I can think of are
Existential types
def foo(l: List[Option[_]]) = …
Higher kinded type parameters
case class A[K[_],T](a: K[T])
Ignored variables
val _ = 5
Ignored parameters
List(1, 2, 3) foreach { _ => println(“Hi”) }
Wildcard patterns
Some(5) match { case Some(_) => println(“Yes”) }
Wildcard imports
import java.util._
Hiding imports
import java.util.{ArrayList => , }
Joining letters to punctuation
def bang_!(x: Int) = 5
Assignment operators
def foo_=(x: Int) { … }
Placeholder syntax
List(1, 2, 3).map (_ + 2)
_+2匿名函数 f=>f+2, f是int
List((1,1), (2,2), (3,3)) map (_._2)
f=>f._2, f是Tuple,_2表示元组的第二个元素
List(1,2,3)
val m = Map("one"->1,"two"->2,"three"->3)m.foldLeft(0)(_+_._2)
第一个_表示取迭代前一个计算结果,
Partially applied functions
List(1, 2, 3) foreach println _
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.
转载
http://stackoverflow.com/questions/8000903/what-are-all-the-uses-of-an-underscore-in-scala
- scala _的用法
- Scala-"_"的用法
- Scala下划线“_”的用法
- Scala中中下划线(_)的用法
- 细数Scala下划线“_”的用法
- 细数Scala下划线“_”的用法
- 细数Scala下划线“_”的用法
- 细数Scala下划线“_”的用法
- 细数Scala下划线“_”的用法
- SCALA下划线_用法
- scala的下划线用法
- scala 通配符的用法
- scala中_的作用
- scala下划线的使用(_)
- scala中=>的用法
- scala中下划线的用法
- scala List集合的用法
- scala中Map的用法
- iOS开发中的公共方法
- php【基础学习十八】ftp
- cookie的几个问题
- Node.js 多进程
- oc 学习(归档)
- scala _的用法
- 最全的常用正则表达式大全
- 获取NSArray的前几个元素,取数组中某个元素
- 全站 HTTPS 来了
- 如何在mycncart设置阿里云免费企业邮箱的SMTP邮件发送
- Node.js JXcore 打包
- Android Studio使用指南
- SVD在推荐系统中的应用【推荐】
- mycncart 商品筛选 filter 模组设定教程