scala隐式转换实例

关于scala语言的隐式转换特性,其他博客的介绍已有不少,这里只是附上一个写代码过程中实际用到的例子:

 

1. 扩充Traversable特征的功能

package com.flute.collection
import java.util import scala.collection.mutable.ListBuffer
/** * Created by xpli on 02/06/16. */ class RichTraversable[A](traver: Traversable[A]) { def groupCount(): Traversable[(A, Int)] = traver.map((_, 1)).groupBy(_._1).map(g => (g._1, g._2.size)) def distinctBy[K](f: A => K): Traversable[A] = { val newBuilder = new ListBuffer[A] val seen = collection.mutable.HashSet[K]() for (x <- traver) { val k = f(x) if (!seen(k)) { newBuilder += x seen += k } } newBuilder } def distinctCountBy[K](f: A => K, expr: A => Boolean = expr => true): Int = { var totalCount = 0 val seen = collection.mutable.HashSet[K]() for (x <- traver) { if (expr(x)) { val k = f(x) if (!seen(k)) { totalCount += 1 seen += k } } } totalCount } // def distinctCountBy[K](f: A => K): Int = { // var totalCount = 0 // val seen = collection.mutable.HashSet[K]() // for (x <- traver) { // val k = f(x) // if (!seen(k)) { // totalCount += 1 // seen += k // } // } // // totalCount // } def shuffle(): Traversable[A] = { import collection.JavaConversions._ val jList: util.List[A] = new util.ArrayList[A]() traver.foreach(jList.add) java.util.Collections.shuffle(jList) jList } def safeReduce(op: (A, A) => A): Option[A] = { if (traver.isEmpty) { None } else { Some(traver.reduce(op)) } } def saveToFile(path: String): Unit = com.flute.utils.FileUtil.write(traver, path) }

定义隐式转换函数

package com.flute.common

import com.flute.collection.{PairTraversable, RichTraversable, SeqJoinWrapper, StrSeqWrapper}

/**
  * Created by xpli on 2016/5/28.
  */
object Implicits {
implicit def toRichTraver[A](traver: Traversable[A]) = new RichTraversable[A](traver)


}

 

 

使用示例:

object test {

  def main(args: Array[String]) {

//保存保存到文件
import com.flute.common.Implicits._
val lst = Traversable("qaz", "wsx", "123")
lst.saveToFile("test.txt")

//随机排序
lst.shuffle().foreach(println)

}

 

}

 

posted on 2017-02-20 09:42  taich-flute  阅读(224)  评论(0编辑  收藏  举报

导航