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

2

9

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.

New answered 17/12, 2014 at 15:43 Comment(0)
S
7

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))
Strouse answered 17/12, 2014 at 16:1 Comment(3)
Hi! Thanks for the answer. I understand it a little bit more now. Let's say, I have this expression, that should be an (String, JsValue): val name: (String, JsValue) = "name" -> teacher.name.map(JsString(_)).getOrElse(JsNull) How to I explicitly tell that line I should be an (String, JsValue)? Right now I keep getting the "Inferred type containing Product" error. BTW: JsString and JsNull inherited from JsValue (spray-json lib)New
Try putting the type annotation on the right hand side of the expression? The only other thing I can suggest is to break up the line so you can see which specific part is causing the problem.Strouse
Indeed, something else was causing the problem. Thanks for the advice!New
V
1

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)

Varistor answered 17/12, 2014 at 16:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.