相关疑难解决方法(0)

scala泛型约束如何对可空类型起作用

我已经尝试了两种方法将泛型类型参数约束为可空类型,但两者似乎都有一些意想不到的问题.

第一次尝试(使用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)

generics scala nullable constraints

14
推荐指数
1
解决办法
4692
查看次数

为什么Unit不在Scala中扩展产品?

在Scala中,为什么不像*类和case类(包括"空"类,如in 和case对象)那样Unit扩展Product特征?Tuplecase class Empty()

Unit(单位值()更具体)绝对是空产品和元组.例如,它以无形的方式使用.

types scala tuples case-class

10
推荐指数
1
解决办法
327
查看次数

Null、Nil 和 Nothing 之间有什么区别?

我正在学习 Scala 并且对下一个类型之间的差异感到有些困惑:“Null”、“Nil”和“Nothing”。

有人可以帮我解释一下区别吗?据我所知,“Nil”用于描述一个空列表。

scala

8
推荐指数
2
解决办法
6616
查看次数

理解scala.Nothing类型

根据 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你能否澄清更多关于无类型的信息。任何例子,解释。

谢谢!

scala nothing

4
推荐指数
1
解决办法
1355
查看次数

Scala中的单位与无

我想澄清一些关于Unit和的细节Nothing.

例如:

def unit(companyId: Int): Unit = {}

def Nothing(companyId: Int): scala.Nothing = {}
Run Code Online (Sandbox Code Playgroud)

根据该文件,Unit在Scala是非常相似voidJava.但

test("test Unit and Nothing") {
  println(unit(1))
}
Run Code Online (Sandbox Code Playgroud)
  • Unit 回归 - ()

  • Nothing 没有任何回报.

为什么Scala有返回的溢出类型?为什么Scala不能代替?UnitNothingNothingUnit

types scala nothing

2
推荐指数
1
解决办法
869
查看次数

编写一个返回Nothing的scala方法

- >我们write a scala method的退货类型Nothing怎么样?

- >我们ever need to write such methods呢?有useful scenarios吗?

scala

2
推荐指数
1
解决办法
774
查看次数

标签 统计

scala ×6

nothing ×2

types ×2

case-class ×1

constraints ×1

generics ×1

nullable ×1

tuples ×1