[英]Scala upper and lower type bound
我在Scala中找到一种方法来同时强加一个上,下类型约束时遇到了麻烦。 我需要制作一个泛型函数,其中类型参数既可哈希(AnyRef的子类型)又可空(Null的超类型)。
我可以这样实现前者:
def foo[T <: AnyRef](t: T) = ???
后者是这样的:
def bar[T >: Null)(t: T) = ???
有没有办法我可以同时做两个呢? 谢谢。
那这个呢?
def foo[T >: Null <: AnyRef](t: T) = ???
它应该工作。 那是:
foo(42) // does not compile
foo(null) // compiles
foo("hello") // compiles
可以将任何类型作为AnyRef
的子类的类型赋值为null
,因此您不需要上限。
def foo[T <: AnyRef](x: T) = x
foo(null) // returns null
就是说,由于您需要能够对值进行哈希处理,因此应注意,如果尝试取消引用null
(例如null.hashCode
),则会得到NullPointerException
。 例如:
def foo[T <: AnyRef](x: T) = x.hashCode
foo(null) // Throws an NPE
此外,强烈建议不要在Scala程序中使用null
。 牢记所有这些,我认为您可能真正想要的是这样的东西,它适用于任何类型:
def foo[T](x: Option[T]) = x.hashCode
def foo(None) // Works. None is equivalent to no value (and Option(null) == None).
def foo(Some(1)) // Works. Note an Int isn't an AnyRef or nullable!
def foo(Some("Hello, world!")) // Works
def foo(Option(null)) // Works.
def foo(Option(z)) // Works, where z can be any reference type value, including null.
Option[T]
是处理未定义值(例如, 可为null的类型 )的功能性手段,并且适用于任何类型T
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.