views:

175

answers:

3

I have a helper method:

def controlStructure[T <: SomeObject](exceptions: Class[_]*)(body: => T) = { 
    try { 
        val tempObject = body 
        tempObject.callSomeMethod 
        Some(tempObject) 
    } catch { 
        case e if (exceptions.contains(e.getClass)) => None 
    } 
} 

called with:

controlStructure[MySomeObject](classOf[Exception]) { getMySomeObjectSomehow } 

the main point of which is to call the 'callSomeMethod' on the entity passed in (for example loaded from ORM), it incidentally wraps things up in exception handling too.

I would now like to add a new method which does the same thing but for a collection (java.util.List) of T.

I am unsure of the syntax, and structures to work with a collection of T in the method signature, and abstract type param definitions.

Thanks for your help.

A: 

There's no pass by name vararg in Scala. You have to pass a function if you want this. See this ticket of an enhancement request to this effect.

Daniel
+1  A: 

With a scala list, you are wanting something like this (I think):

  def controlStructure[T <: SomeObject](exceptions: Class[_]*)(body: => List[T]) = {
    try {
      val tempObject = body
      tempObject.foreach { _.callSomeMethod() }
      Some(tempObject)
    }
    catch {
      case e if (exceptions.contains(e.getClass)) => None
    } 
  }

I haven't worked with Java lists in scala, so I'm guessing you could do it with java.util.List like this:

  def controlStructure[T <: SomeObject](exceptions: Class[_]*)(body: => java.util.List[T]) = {
    import scala.collection.JavaConversions._
    try {
      val tempObject = body
      tempObject foreach { _.callSomeMethod() }
      Some(tempObject)
    }
    catch {
      case e if (exceptions.contains(e.getClass)) => None
    } 
  }
Mitch Blevins
Hi, thanks for your help. Sorry I forgot to mention, I am using Scala 2.8.0-Beta1-RC2, so I assumed I could just automatically call 'foreach' on tempObject without the need for the .toArray stuff by importing 'scala.collection.JavaConversions._', however it is telling mefound : java.lang.Objectrequired:java.util.List[MySomeObject]Any ideas?
Edited to use JavaConversions and it works as shown for me (using Scala 2.8.0.r19890). Can you confirm your code matches?
Mitch Blevins
Hi. My JavaConversions import is at the top of the file, and I am passing a java.util.ArrayList[MySomeObject] with one item into the controlStructure construct. The only other difference I can think of is that my SomeObject is part of my domain layer, and so inherits from various traits?
A: 

Thanks for your help Mitch. It turns out the answer is in this case to specify the return type of the method, as java.util.List[T], as for once Scala is not using its magic type inference to sort everything out. I am not sure why.

Perhaps someone can answer that ?