【问题标题】:Null as parameter default value in scala produces type mismatch errorscala中的null作为参数默认值会产生类型不匹配错误
【发布时间】:2019-07-22 21:21:56
【问题描述】:

为了进行类似的重载调用

val myPage: DocumentType;
func()
func(myPage)

我写了一个函数:

def func(page: DocumentType = null): Unit = {...}

但收到以下错误:

type mismatch; found : Null(null) required: DocumentType

当我将 DocumentType 更改为 String 时,错误消失了。第一个问题:为什么? DocumentType 是我无法更改的库中的类型,具有以下定义:

type DocumentType <: Document
trait Document

我不希望在每个客户端调用中都将实际参数包装到 Option(如 Option(myPage)),但还有其他选项可以获得类似的吗?

【问题讨论】:

  • 可以分享或指出DocumentType的定义吗?
  • @LuisMiguelMejíaSuárez 1) 类型 DocumentType <: document trait>

标签: scala types null


【解决方案1】:

你可以像这样重载函数

def func(): Unit = { }  // do what you would do with null
def func(page: DocumentType): Unit = { }  // do what you would do with a DocumentType

您可以通过让两者都调用其他一些私有函数来使其保持干燥来抽象实现。然后您可以致电func()func(new DocumentType())

原始答案(不太好)

def func(page: DocumentType): Unit = func(Some(page))
def func(page: Option[DocumentType] = None): Unit = ???

意味着您不需要求助于null。你失去了干净的 API,你可以调用

val d = new DocumentType()
func()
func(d)
func(Some(d))
func(None)

【讨论】:

  • 感谢您的建议。仅出于教育目的,是否有可能保持为空?
  • @AlexStamper 通常建议尽可能避免 null
【解决方案2】:

这样的事情应该可以工作:

trait Document

trait DocumentFunc {
  // The trick is to tell the compiler that your type can be nullable.
  type DocumentType >: Null <: Document

  def fun(page: DocumentType = None.orNull): Unit = {
    println(page)
  }
}

显然,问题在于,由于您只将上限设置为Document,编译器将拒绝null,因为DocumentType 可能被覆盖为Nothing
而且“显然”null 不能用在需要 Nothing 的地方。

第一个免责声明:我同意 Joel Berkeley 的观点,您应该避免使用 null,我更喜欢他的解决方案。
我只是想回答真正的问题:“为什么它不起作用”

第二个免责声明:我使用 None.orNull 只是为了没有明确的 null - 那只是因为我使用的 linter 不允许使用 null
如果你愿意,你可以改变它。

第三个免责声明:Type Members 几乎总是可以被Type Parameters 更改,这(通常) 更容易使用,并且更“类型安全"
Type Members恕我直言,只应在您真正需要它们时使用,例如 path dependent types - 更多信息可以在 here 找到。

第四个免责声明:使用nullUnit(如果你有的话,再加上vars,是使用Scala 的症状Java(通常) 是对语言的错误使用。不过,这只是我的看法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 2016-11-24
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多