Scala代表Option元组

时间:2015-11-02 14:42:49

标签: scala

如何将某个类型的元组的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)

3 个答案:

答案 0 :(得分:9)

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

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

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

var c = Option((1, 1))

答案 1 :(得分:2)

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

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

答案 2 :(得分:0)

实际上这不是关于元组的。以下代码无效:

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

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

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

如果您需要,可以查看更多:Scala Option