Search code examples
scalacollectionscompile-timetypechecking

Enforce Scala Seq to use a single type only (no LUB)


I would like to create and use a Seq[T] collection in Scala and ensure that it only use one type. So if I use:

val l = List(1, 2, 2.0)

a compile time error should occur - List elements should all be Double or all Int.


Solution

  • Consider -Xlint:infer-any compiler flag

    Warn when a type argument is inferred to be Any

    which in combination with fatal warnings at least prevents worst case LUB scenario where Any is inferred

    scala -Xlint:infer-any -Werror -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.
    

    however note this will not help if LUB is narrower than Any, for example

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

    raises no warning. Another flag that might help is -Wnumeric-widen

    Warn when numerics are widened.

    for example

    scala -Wnumeric-widen -Xlint:infer-any -Werror -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.