强制Scala Seq仅使用单一类型(无LUB)

问题描述 投票:4回答:1

我想在Scala中创建并使用Seq[T]集合并确保它仅使用一种类型。因此,如果我使用:

val l = List(1, 2, 2.0)

应发生编译时错误-List元素应全部为Double或全部Int

scala collections compile-time typechecking
1个回答
0
投票

考虑-Xlint:infer-any编译器flag

警告类型参数推断为Any

结合致命警告,至少可以防止推断出Any的最坏情况的LUB场景>

scala -Xlint:infer-any -Xfatal-warnings -e 'List(42, 3.14, "picard")'
warning: a type was inferred to be `Any`; this may indicate a programming error.
List(42, 3.14, "picard")
^
error: No warnings can be incurred under -Werror.

但是请注意,如果LUB小于Any,这将无济于事

scala -Xlint:infer-any -Xfatal-warnings -e 'Vector(List(1), Set(2))'

不提出警告。另一个可能有用的标志是-Wnumeric-widen

当数字扩大时警告。

例如

scala -Wnumeric-widen -Xlint:infer-any -Xfatal-warnings -e 'def f(i: Int, d: Double): List[Double] = List(i, d)'
warning: implicit numeric widening
def f(i: Int, d: Double): List[Double] = List(i, d)
                                              ^
error: No warnings can be incurred under -Werror.
© www.soinside.com 2019 - 2024. All rights reserved.