我已经尝试了两种方法将泛型类型参数约束为可空类型,但两者似乎都有一些意想不到的问题.
第一次尝试(使用T <:AnyRef):
scala> def testAnyRefConstraint[T <: AnyRef](option:Option[T]):T = {
| //without the cast, fails with compiler error:
| // "found: Null(null) required: T"
| option getOrElse null.asInstanceOf[T]
| }
testAnyRefConstraint: [T <: AnyRef](Option[T])T
scala> testAnyRefConstraint(Some(""))
res0: java.lang.String =
scala> testAnyRefConstraint(Some(0))
<console>:16: error: inferred type arguments [Int] do not conform to method testAnyRefConstraint's type parameter bounds [T <: AnyRef]
testAnyRefConstraint(Some(0))
Run Code Online (Sandbox Code Playgroud)
这似乎完全符合我的要求,但我不明白为什么需要将null转换为T.
第二次尝试(使用T>:Null):
scala> def testNullConstraint[T >: Null](option:Option[T]):T = {
| option getOrElse null
| }
testNullConstraint: [T >: Null](Option[T])T
scala> …
Run Code Online (Sandbox Code Playgroud) 在Scala中,为什么不像*类和case类(包括"空"类,如in 和case对象)那样Unit
扩展Product
特征?Tuple
case class Empty()
Unit
(单位值()
更具体)绝对是空产品和元组.例如,它以无形的方式使用.
我正在学习 Scala 并且对下一个类型之间的差异感到有些困惑:“Null”、“Nil”和“Nothing”。
有人可以帮我解释一下区别吗?据我所知,“Nil”用于描述一个空列表。
根据 scala 规范, scala.Nothing 类型 - 所有类型的按钮。类型“Nothing”存在,但 Nothing 的实例不存在。
这个怎么运作:
def ??? : Nothing = throw new NoImplementedError
def sys.error(message: String): Nothing = throw new RuntimeException()
def sys.exit(status: Int): Nothing = {...}
Run Code Online (Sandbox Code Playgroud)
但实际上,所有提到的方法都返回异常。例外def sys.exit
你能否澄清更多关于无类型的信息。任何例子,解释。
谢谢!
我想澄清一些关于Unit
和的细节Nothing
.
例如:
def unit(companyId: Int): Unit = {}
def Nothing(companyId: Int): scala.Nothing = {}
Run Code Online (Sandbox Code Playgroud)
根据该文件,Unit
在Scala是非常相似void
的Java
.但
test("test Unit and Nothing") {
println(unit(1))
}
Run Code Online (Sandbox Code Playgroud)
Unit
回归 - ()
Nothing
没有任何回报.
为什么Scala有返回的溢出类型?为什么Scala不能代替?Unit
Nothing
Nothing
Unit
- >我们write a scala method
的退货类型Nothing
怎么样?
- >我们ever need to write such methods
呢?有useful scenarios
吗?