gpt4 book ai didi

Scala类型约束不允许为空

转载 作者:行者123 更新时间:2023-12-04 13:20:26 24 4
gpt4 key购买 nike

我有以下Scala代码:

class X[T1 <: AnyRef] {
var _x : T1 = null
}

代码_x = null突出显示为错误:
error: type mismatch;
found : Null(null)
required: T1
var _x : T1 = null : T1

如果我添加Null类型约束,则一切正常。为什么会这样? Scala将AnyRef定义为与java.lang.Object等效,当然可以为空。

最佳答案

代替

var _x : T1 = null
var _x : T1 = _
Scala语言规范中的解释:

A variable definition var x: T = _ can appear only as a member of a template. It introduces a mutable field with type T and a default initial value. The default value depends on the type T as follows:

0 if T is Int or one of its subrange types,
0L if T is Long,
0.0f if T is Float,
0.0d if T is Double,
false if T is Boolean,
() if T is Unit,
null for all other types T.

关于Scala类型约束不允许为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11215915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com