Scala 抽象方法参数问题,T 列表
我有一个辅助方法:
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
}
}
调用方式:
controlStructure[MySomeObject](classOf[Exception]) { getMySomeObjectSomehow }
其要点是在传入的实体上调用“callSomeMethod”(例如从 ORM 加载),它也顺便将事情包装在异常处理中。
我现在想添加一个新方法,它执行相同的操作,但对于 T 的集合 (java.util.List)。
我不确定语法以及在方法签名中使用 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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于 scala 列表,你想要这样的东西(我认为):
我没有在 scala 中使用过 Java 列表,所以我猜你可以使用 java.util.List 来做到这一点,如下所示:
With a scala list, you are wanting something like this (I think):
I haven't worked with Java lists in scala, so I'm guessing you could do it with java.util.List like this:
Scala 中没有通过名称 vararg 进行传递。如果你想要这个,你必须传递一个函数。请参阅对此效果的增强请求的此票据。
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.
谢谢你的帮助,米奇。事实证明,在这种情况下,答案是指定方法的返回类型,如 java.util.List[T],因为 Scala 没有使用其魔术类型推断来对所有内容进行排序。
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.