上週給同事分享一些不常用但很有用的知識點,這裏把做的材料也分享出來
zipWithIndex
(1 to 10).zipWithIndex
call by Name and call By value
def something() = {
println("calling something")
1 // return value
}
//call by value version side-effect of the passed-in function call only hadppend once ,however call-by-name version side-effect happended twice
//This is because call-by-value functions compute the passed-in expression's value before calling the function, thus the same value is accessed every time. However, call-by-name functions recompute the passed-in expression's value every time it is accessed.
def callByValue(x: Int) = {
println("x1=" + x)
println("x2=" + x)
}
def callByName(x: => Int) = {
println("x1=" + x)
println("x2=" + x)
}
partition && span
val x = (1 to 10 )
x.parition( _ % 2 == 1)
x.span( _ % 2 == 1 )
def quickSort(xs: List[Int]): List[Int] = xs match {
case Nil => Nil
case head :: tail =>
val (before, after) = tail.partition(_ < head)
quickSort(before) ++ (head :: quickSort(after))
}
tuppled
def mult(d1:Double,d2:Double,d3:Double) = d1 * d2 * d3
val x = (2.2,2.3,2.4)
mult(x._1,x._2,x._3)
//cool
val multTupled = Function.tupled(mult _)
multTupled(x)
val multUntupled = Function.untupled(multTupled)
grouped
val x = (1 to 10 )
x.grouped(2).toList
fold
(0 /: x) (_ + _) //
x.foldLeft(0)(_ + _)
implicit def getHadoopConf(resources: Seq[String]): Configuration = {
val config = resources.foldLeft(new Configuration()) {
case (conf, path) ⇒ conf.addResource(new Path(path))
conf
}
config
}
make && fill
List.make(2,"10")
List.fill(2)("10")
List.tabulate(5)(_ * 2 )
mkString
x.mkString("[","$$","]")
transpose
val x = Seq(Seq(1,2,3),Seq(4,5,6))
xs.transpose
implicit
implicit val x = "a"
implicitly[String]
implicitly[Int]