標籤:
Scala 作為一門函數式程式設計語言,對習慣了指令式程式設計語言的同學來說,會不大習慣,這裡除了思維方式之外,還有文法層面的,比如 underscore(底線)就會出現在多種場合,令初學者相當疑惑,今天就來總結下 Scala 中底線的用法。
1、存在性類型:Existential typesdef foo(l: List[Option[_]]) = ...2、高階型別參數:Higher kinded type parameterscase class A[K[_],T](a: K[T])3、臨時變數:Ignored variablesval _ = 54、臨時參數:Ignored parametersList(1, 2, 3) foreach { _ => println("Hi") }5、通配模式:Wildcard patternsSome(5) match { case Some(_) => println("Yes") }val (a, _) = (1, 2)for (_ <- 1 to 10)6、通配匯入:Wildcard importsimport java.util._7、隱藏匯入:Hiding importsimport java.util.{ArrayList => _, _}8、串連字母和標點符號:Joining letters to punctuationdef bang_!(x: Int) = 59、預留位置文法:Placeholder syntaxList(1, 2, 3) map (_ + 2)_ + _ 10、偏應用函數:Partially applied functionsList(1, 2, 3) foreach println _11、初始化預設值:default valuevar i: Int = _12、訪問元組:tuple getterst._2 13、參數序列:parameters Sequence _*作為一個整體,告訴編譯器你希望將某個參數當作參數序列處理!例如val s = sum(1 to 5:_*)就是將1 to 5當作參數序列處理。
這裡需要注意的是,以下兩種寫法實現的是完全不一樣的功能:
foo _ // Eta expansion of method into method valuefoo(_) // Partial function application
Example showing why foo(_) and foo _ are different:
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.
Refer:
[1] What are all the uses of an underscore in Scala?
http://stackoverflow.com/questions/8000903/what-are-all-the-uses-of-an-underscore-in-scala
[2] Scala punctuation (AKA symbols and operators)
http://stackoverflow.com/questions/7888944/scala-punctuation-aka-symbols-and-operators/7890032#7890032
[3] Scala中的底線到底有多少種應用情境?
http://www.zhihu.com/question/21622725
[4] Strange type mismatch when using member access instead of extractor
http://stackoverflow.com/questions/9610736/strange-type-mismatch-when-using-member-access-instead-of-extractor/9610961
[5] Scala簡明教程
http://colobu.com/2015/01/14/Scala-Quick-Start-for-Java-Programmers/
淺談 Scala 中底線的用途