我在 scala 中找不到一种同时施加上限和下限类型的方法。我需要创建一个泛型函数,其中类型参数既可散列(AnyRef 的子类型)又可为空(Null 的超类型)。
我可以这样实现前者:
def foo[T <: AnyRef](t: T) = ???
Run Code Online (Sandbox Code Playgroud)
后者是这样的:
def bar[T >: Null)(t: T) = ???
Run Code Online (Sandbox Code Playgroud)
有没有办法可以同时做这两件事?谢谢。
那这个呢?
def foo[T >: Null <: AnyRef](t: T) = ???
Run Code Online (Sandbox Code Playgroud)
它应该有效。那是:
foo(42) // does not compile
foo(null) // compiles
foo("hello") // compiles
Run Code Online (Sandbox Code Playgroud)