How to fix the Product Type Inferred error from Scala's WartRemover tool

3.5k views Asked by At

I'm using WartRemover tool to avoid possible errors in my Scala 2.11 code.

Specifically, I want to know how to fix the "Product Type Inferred" error.

Looking at the repo documentation, I can only see the failure example, but I would like to know how I'm suppose to fix that error:

https://github.com/puffnfresh/wartremover#product.

Doing my homework, I end up with this other link that explains how to fix Type Inference Failures errors https://blog.cppcabrera.com/posts/scala-wart-remover.html. And I quote "If you see any of the warnings below, the fix is usually as simple as providing type annotations" but I don't understand what that means. I really need a concrete example.

2

There are 2 answers

3
lmm On BEST ANSWER

Product is a very abstract, high-level type, with very few constraints. When the inferred type is Product, that's usually an indication that you made a mistake. E.g. if you have:

List((1, "hi", 0.4f), (2, "bye"), (3, "aloha", 7.2f))

Then this will compile ok, giving you a List[Product]. But, just as when Any is inferred, this is probably a bug - you probably meant it to be a List[(Int, String, Float)] and meant to have a third entry in the middle tuple.

If you really do want a List[Product], you can avoid getting warned about it by giving the type argument explicitly:

List[Product]((1, "hi", 0.4f), (2, "bye"), (3, "aloha", 7.2f))
0
nitishagar On

Type annotation is nothing but explicitly specifying the type, instead of leaving it for the type inference system to work on.

Simplest example in this case can be:

val element = 2

Currently the inferred type is Int, If you want to have more control over the type like specify Byte, Short, Long, Double, you can explicitly give the type as:

val element: Double = 2

Type annotation is also required for public methods as

Type inference may break encapsulation in these cases, because it depends on internal method and class details

(Source)