简体   繁体   English

Scala上下类型边界

[英]Scala upper and lower type bound

I'm having trouble finding a way in scala to simultaneously impose an upper and lower type bound. 我在Scala中找到一种方法来同时强加一个上,下类型约束时遇到了麻烦。 I need to make a generic function where the type parameter is both hashable (subtype of AnyRef) and nullable (supertype of Null). 我需要制作一个泛型函数,其中类型参数既可哈希(AnyRef的子类型)又可空(Null的超类型)。

I could achieve the former like this: 我可以这样实现前者:

def foo[T <: AnyRef](t: T) = ???

And the latter like this: 后者是这样的:

def bar[T >: Null)(t: T) = ???

Is there a way that I can do both simultaneously? 有没有办法我可以同时做两个呢? Thanks. 谢谢。

What about this? 那这个呢?

def foo[T >: Null <: AnyRef](t: T) = ???

It should work. 它应该工作。 That is: 那是:

foo(42) // does not compile 
foo(null) // compiles
foo("hello") // compiles

Any type that is a subclass of AnyRef can be assigned the value null , so you do not need the upper bound. 可以将任何类型作为AnyRef的子类的类型赋值为null ,因此您不需要上限。

def foo[T <: AnyRef](x: T) = x
foo(null) // returns null

That said, since you need to be able to hash the value, it should be noted that if you attempt to dereference null (eg null.hashCode ) you will get a NullPointerException . 就是说,由于您需要能够对值进行哈希处理,因此应注意,如果尝试取消引用null (例如null.hashCode ),则会得到NullPointerException For example: 例如:

def foo[T <: AnyRef](x: T) = x.hashCode
foo(null) // Throws an NPE

Furthermore, any use of null in Scala programs is strongly discouraged. 此外,强烈建议不要在Scala程序中使用null Bearing all that in mind, I think what you might really want is something like this, which works for any type: 牢记所有这些,我认为您可能真正想要的是这样的东西,它适用于任何类型:

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] is a functional means of dealing with undefined values (such as nullable types ), and it works for any type T . Option[T]是处理未定义值(例如, null的类型 )的功能性手段,并且适用于任何类型T

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM