0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Another undesirable side-effect is that List(1) :+ 30000000000L compiles, and doesn't even throw anything.
1

The applicable method :+ is available on the List class itself, so the compiler doesn't bother looking up any other methods with the same name added by implicits.

I think the best solution may be WartRemover, as it happens this case is covered by the built-in AnyVal wart.

1 Comment

Thanks, Alexey, but unfortunately my code has to run in a dynamically created ScalaFiddle where I won't be able to use the WarRemover plugin.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.