开发者

Scala abstract method param question, List of T

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开发者_Python百科 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.


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
    } 
  }


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜