How to define a function which accept both Seq[T] and ParSeq[T] as parameter?

荒凉一梦 提交于 2019-12-12 04:31:24

问题


In many cases, I want to apply the same filter or map function to a Seq or ParSeq collection. However I don't want to write the code twice.

def fun(data:ParSeq[String], num_start:Int,num_end:Int) = {
    data filter { x=>
      val temp = extract_number(x)
      num_start <= temp && temp <= num_end
    }
  }

Like the code above, for a Seq[String] I need to apply fun, I have to rewrite it again and the content are exactly the same. How can I avoid it?


回答1:


You can use GenSeq[String].

Both ParSeq and Seq extends GenSeq, this is typically used in order to have functions that will use parallel or sequential operations depending on the type of collection you pass to them.




回答2:


Try this

def fun(data:GenSeq[String], num_start:Int,num_end:Int) = {
    data filter { x=>
      val temp = extract_number(x)
      num_start <= temp && temp <= num_end
    }
  }

GenSeq is a trait and it is extended [or implemented] by both ParSeq and Seq



来源:https://stackoverflow.com/questions/42826571/how-to-define-a-function-which-accept-both-seqt-and-parseqt-as-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!