scala 从函数返回元组
假设我有这样的东西:
def f () = {
var v = someLookupToV()
match v {
case Some(v) => (v.id, someOtherLookup(v.id))
case None => None // <<-- doesn't work, but I'm not sure what to put there!
}
}
有点假设 someLookupToV 返回一些对象,它有一个字段 id,然后我有一些基于 v.id 的其他查找。我想将这两个值作为元组返回。但是如果 Some(v) 不匹配任何内容我该怎么办?我要返回什么?无和(无,无)不起作用。 Scala 接受了 (null,null) 但我不知道这是否是正确的做法......
Lets say I have something like this:
def f () = {
var v = someLookupToV()
match v {
case Some(v) => (v.id, someOtherLookup(v.id))
case None => None // <<-- doesn't work, but I'm not sure what to put there!
}
}
Sort of assuming that someLookupToV returns some object, that has a field id, and then I have some other lookup based on v.id. I want to return both values as a tuple. But what do I do if Some(v) doesn't match anything? What do I return? None and (None,None) didnt' work. Scala accepted (null,null) but I've got no clue if that's the right thing to do...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不会让函数返回
(Int, Option[Int])
,而是Option[(Int, Option[Int])]
:或者更短一些:
I would not have the function return
(Int, Option[Int])
, but insteadOption[(Int, Option[Int])]
:or, somewhat shorter:
如果您想返回 (None, None),您的“case Some”行需要返回 (Option, Option) 的元组。
正如示例中所写,您的
case Some
正在返回 (Int, Option)。假设您的v.id
是一个 Int 并且 someOtherLookup 返回一个 Option。If you want to return (None, None), your "case Some" line needs to return a tuple of (Option, Option).
As written in your example, your
case Some
is returning (Int, Option). That's assuming yourv.id
is an Int and someOtherLookup returns an Option.