Tried to avoid a specific literal type widening with an implicit class:
implicit class keepAsListOfInt(val listOfInt: List[Int]) extends AnyVal {
def :+(long: Long): List[Int] = listOfInt :+ long.toInt
}
// Won't compile - already widened to List[AnyVal]
val listOfInt: List[Int] = List(1) :+ 2L
But since the compiler has already widened the expression List(1) :+ 2L
to List[AnyVal]
the implicit conversion is never called. Can I somehow enforce the conversion implicitly?
UPDATE - Thanks to sachav's reply and Alexey's valid concerns, the following code seems to do the job:
import scala.language.implicitConversions
implicit def listAnyValToListInt(l: List[AnyVal]): List[Int] = l.map {
case n: Int => n
case n: Long if n < Int.MinValue =>
throw new IllegalArgumentException("Can't cast too small Long to Int: " + n)
case n: Long if n > Int.MaxValue =>
throw new IllegalArgumentException("Can't cast too big Long to Int: " + n)
case n: Long => n.toInt
case v =>
throw new IllegalArgumentException("Invalid value: " + v)
}
val valid: List[Int] = List(1) :+ 2
val invalid: List[Int] = List(1) :+ 30000000000L // fails at runtime
It would still be nice though if there was a compile-time solution.
An ugly solution would be to accept the conversion to List[AnyVal]
, and add an implicit conversion from List[AnyVal]
to List[Int]
:
implicit def listAnyValToListInt(l: List[AnyVal]): List[Int] = l.map {
case e: Int => e
case e: Long => e.toInt
}
val listOfInt: List[Int] = List(1) :+ 2L //compiles
Although an undesirable side-effect will be that an expression such as val listOfInt: List[Int] = List(1) :+ 2.0
will throw a MatchError.