【问题标题】:Scala represent an Option tupleScala 表示一个 Option 元组
【发布时间】:2015-11-03 01:43:48
【问题描述】:

如何将某个类型的元组的Option显式设置为None?

scala> var c = Some(1,1)
c: Some[(Int, Int)] = Some((1,1))

scala> c = None
<console>:11: error: type mismatch;
 found   : None.type
 required: Some[(Int, Int)]
       c = None
           ^

scala> None()
<console>:11: error: None.type does not take parameters
       None()
           ^

scala> c = None()
<console>:11: error: None.type does not take parameters
       c = None()
               ^

scala> c = None.Int
<console>:11: error: value Int is not a member of object None
       c = None.Int
                ^

scala> c = None(Int, Int)
<console>:11: error: None.type does not take parameters
       c = None(Int, Int)
               ^

scala> c = (None, None)
<console>:11: error: type mismatch;
 found   : (None.type, None.type)
 required: Some[(Int, Int)]
       c = (None, None)

【问题讨论】:

  • 在第一次使用时明确声明类型。这里的推论过于精确/限制性 - 一些而不是选项。 var c: Option[(Int, Int)] = Some((1,1))

标签: scala


【解决方案1】:

正如@DidierDupont 指出的那样-您对c 的第一个声明推断其类型是Some[(Int, Int)],而不是Option[(Int, Int)]。声明c如下,你应该没问题:

var c: Option[(Int, Int)] = Some((1, 1))

或者,正如 Gabriele Petronella 指出的那样,只是

var c = Option((1, 1))

【讨论】:

  • 或只是val c: Option((1, 1))。这也是使用自动元组,这可能不是最好的主意
  • Gabriele 说了什么,加上这个解释 - stackoverflow.com/a/5998559/409976.
  • @KevinMeredith 我已经删除了自动元组。感谢您的参考。
【解决方案2】:

您声明了 c = Some(1,1),将类型设置为 Some。你真的想要一个 Option 类型,所以尝试声明类型:

var c:Option[(Int,Int)] = Some(1,1)
c = None

【讨论】:

  • 方法的返回参数是什么类型?
  • 如果方法定义为返回类型Some,你仍然可以将变量声明为Option类型。
【解决方案3】:

实际上这与元组无关。以下代码将不起作用:

var a = Some("String")
a = None

因为 Scala 有一个 Some[T] 类型,它是 Option[T] 的子类,就像 None 一样,这意味着 Some[T] 和 None 类型处于相同的继承级别。因此,由此我们可以说像其他人提到的那样明确声明类型会起作用。

var a: Option[(Int, Int)] = Some((1, 1))

如果您愿意,可以查看更多信息:Scala Option

【讨论】:

    猜你喜欢
    • 2013-02-13
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    • 2016-01-05
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多