Thursday, October 1, 2009

Multiple type bounds on a generic parameter

Suppose you want to declare a method to take objects that implement two interfaces or parent objects. For example suppose the parameter must implement both Iterable and a function so that you can access the elements of the iterable via object(index). How can you do that in scala?

This topic is derived from How do I setup multiple type bounds in Scala?

  1. scala>def process[R <: Function1[Int,String]with Iterable[String]] (resource:R) = {
  2.      | println("using function:"+resource(0))
  3.      | println("using iterable:"
  4.      | }
  5. process: [R <: (Int) => String with Iterable[String]](R)Unit
  6. // Array is a Function1 and iterable so this works
  7. scala> process (Array("1","2","3"))                                                  
  8. using function:1
  9. using iterable:1

No comments:

Post a Comment