scala 从函数返回元组

发布于 2024-10-28 08:19:39 字数 429 浏览 1 评论 0原文

假设我有这样的东西:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

墨落成白 2024-11-04 08:19:39

我不会让函数返回 (Int, Option[Int]),而是 Option[(Int, Option[Int])]:

def f = someLookupToV match {
  case Some(v) => Some(v.id, someOtherLookup(v.id))
  case None => None
}

或者更短一些:

def f = someLookupToV.map(v => (v.id, someOtherLookup(v.id)))

I would not have the function return (Int, Option[Int]), but instead Option[(Int, Option[Int])]:

def f = someLookupToV match {
  case Some(v) => Some(v.id, someOtherLookup(v.id))
  case None => None
}

or, somewhat shorter:

def f = someLookupToV.map(v => (v.id, someOtherLookup(v.id)))
优雅的叶子 2024-11-04 08:19:39

如果您想返回 (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 your v.id is an Int and someOtherLookup returns an Option.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文