我想在Scala中创建并使用Seq[T]
集合并确保它仅使用一种类型。因此,如果我使用:
val l = List(1, 2, 2.0)
应发生编译时错误-List
元素应全部为Double
或全部Int
。
考虑-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.