您可以为 None 指定类型参数或告诉编译器它是一个 Option[String] 吗? [英] Can you specify type argument for None or tell compiler that it's an Option[String]?
问题描述
我想知道我是否可以在我的代码中写这样的东西:
I wonder if I can write something like this in my code:
None[String]
推荐答案
我很惊讶没有人提到 Option.empty
的存在:
I am surprised that nobody mentioned the existence of Option.empty
:
scala> Option.empty[String]
res0: Option[String] = None
请注意,在许多情况下,只需在需要 Option[String]
的地方使用 None
即可正常工作.或者换句话说,(如 Aleksey Izmailov 所示),以下是正确的:
Note that in many cases simply using None
where an Option[String]
is expected will work fine.
Or in other words, (as shown by Aleksey Izmailov), the following is corrrect:
def f(o: Option[String]) = ...; f(None)
这是因为 None
扩展了 Option[Nothing]
,所以凭借 Option
是协变的(并且 Nothing
> 作为所有其他类型的子类型),对于任何 T
,None
始终与 Option[T]
兼容.
This is because None
extends Option[Nothing]
, so by virtue of Option
being covariant (and Nothing
being a sub-type of every other type), None
is always a compatible with Option[T]
for any T
.
这也是为什么类型归属也是一个很好的选择(对于您确实需要明确选项类型的情况,例如如果需要驱动类型推断):
This is also why type ascription is also a fine alternative (for the cases where you do need to be explicit on the type of options, by example if it is needed to drive type inference):
scala> None: Option[String]
res0: Option[String] = None
这篇关于您可以为 None 指定类型参数或告诉编译器它是一个 Option[String] 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!