spark||flink||scala

scala高级语法之柯里化(curring)和 隐式转换(imp

2019-05-09  本文已影响3人  达微

柯里化(curring)
scala 中 curring 是将一个正常的方法转换为科里化的一个过程
把一个参数列表中的多个参数转换为多个列表
如:①→②

① def m1(a:Int,b:Int)=a+b
② def m2(a:Int)(b:Int) =a+b

隐式转换(implicit)

object Implicit{
def main(args:Array[String]):Unit={
 
implicit val a:Int=10
def m1(a:Int,b:Int)=a+b
def m2(a:Int)(implicit b:Int)=a+b
 
/*def m2(a:Int)(implicit b:Int=1)=a+b*/ //方法参数列表里默认隐式值
println(m2(5))
}
}

隐式转换的注意事项:
①隐式参数值是从上下文环境中寻找,匹配使用implicit修饰的变量,且最多只有一个,与方法参数列表中隐式类型一致,并使用。
②如果匹配到多个,报错。
③如果上下文中没有,则使用方法参数列表中的默认隐式值。
④如果没有默认值,报错。
⑤一个参数列表中只能有一个implicit关键字,implicit放到最后一个列表中,并修饰该列表中的所有参数,如:

def m2(a:Int)(b:Int)(implicit c:Int,d:Int)

案例:

implicitval scala:Int=20
 def m3(a:Int)(b:Int)(implicit c:Int,d:Int)=a+b+c+d
println(m3(5)(5))//结果为 50=5+5+20+20

其中 c,d都从上下文中获得20的值

sortBy

/** Sorts this $Coll according to the Ordering which results from transforming
   *  an implicitly given Ordering with a transformation function.
   *  @see [[scala.math.Ordering]]
   *  $willNotTerminateInf
   *  @param   f the transformation function mapping elements
   *           to some other domain `B`.
   *  @param   ord the ordering assumed on domain `B`.
   *  @tparam  B the target type of the transformation `f`, and the type where
   *           the ordering `ord` is defined.
   *  @return  a $coll consisting of the elements of this $coll
   *           sorted according to the ordering where `x < y` if
   *           `ord.lt(f(x), f(y))`.
   *
   *  @example {{{
   *    val words = "The quick brown fox jumped over the lazy dog".split(' ')
   *    // this works because scala.Ordering will implicitly provide an Ordering[Tuple2[Int, Char]]
   *    words.sortBy(x => (x.length, x.head))
   *    res0: Array[String] = Array(The, dog, fox, the, lazy, over, brown, quick, jumped)
   *  }}}
   */
  def sortBy[B](f: A => B)(implicit ord: Ordering[B]): Repr = sorted(ord on f)


/** Sorts this $coll according to a comparison function.
   *  $willNotTerminateInf
   *
   *  The sort is stable. That is, elements that are equal (as determined by
   *  `lt`) appear in the same order in the sorted sequence as in the original.
   *
   *  @param  lt  the comparison function which tests whether
   *              its first argument precedes its second argument in
   *              the desired ordering.
   *  @return     a $coll consisting of the elements of this $coll
   *              sorted according to the comparison function `lt`.
   *  @example {{{
   *    List("Steve", "Tom", "John", "Bob").sortWith(_.compareTo(_) < 0) =
   *    List("Bob", "John", "Steve", "Tom")
   *  }}}
   */
  def sortWith(lt: (A, A) => Boolean): Repr = sorted(Ordering fromLessThan lt)
上一篇下一篇

猜你喜欢

热点阅读