你能在scala中编写自己的exists方法吗?

时间:2012-06-07 16:29:17

标签: scala

阅读Scala,以及作用于集合的exists方法如何减少代码重复等。

你怎么能写一个类似于存在的函数来自己对集合起作用?有可能吗?

类似于对特定类型起作用的c#扩展方法。

1 个答案:

答案 0 :(得分:9)

当然,你可以使用implicit conversions

来做到这一点
scala> implicit def foo[A](xs: Seq[A]) = new {
     |   def any(f: A => Boolean): Boolean = {
     |     for(x <- xs; if f(x)) return true
     |     false
     |   }
     | }
foo: [A](xs: Seq[A])java.lang.Object{def any(f: A => Boolean): Boolean}

scala> Seq(9, 11, 34).any(_ > 10)
res3: Boolean = true

scala> Seq(9, 11, 34).any(_ > 35)
res4: Boolean = false