1

Is there any static code analyzer that can be used to enforce Type Annotation in Scala. For example, when a developer writes a statement without type annotation as show in the example below, he should get a compile time error

val name="sometime" //This should throw compile time error

This is what I expect the developer to write,

val name: String = "somename" // Type annotation 'String' explicitly specified

I am able to enforce few good practices using Scalastyle plugin in sbt(which throws compile time error when any of the rules specified for ScalastylePlugin is not followed). But I could find any rule that enforce type annotation

PS : Scalastyle does provide provision to create CustomRules(by extending the class ScalariformChecker). But I am just looking for a way to avoid developing custom code

Raj
  • 2,368
  • 6
  • 34
  • 52
  • 1
    _Scalastyle_ has a rule (`PublicMethodsHaveTypeChecker`) which checks that public methods have explicit return types, but otherwise, I think you're out of luck. _Type inference_ is one of the big advantages of _Scala_. Why do you want to force types to be declared explicitly? – Mike Allen May 31 '17 at 02:43
  • have a look at www.codacy.com. It has support for many languages besides scala, but it has a couple of detections of missing type annotation (disclaimer, I work there) – pedrorijo91 May 31 '17 at 09:12
  • @MikeAllen In terms of code readability. Having an explicit type makes it much more easier to understand the code. – Raj May 31 '17 at 15:10
  • 1
    I agree that it can sometimes be clearer to declare the type explicitly, but a lot of the time, it's actually clearer and more readable if you let _Scala_ work its magic. For example: `val x = 1` vs. `val x: Int = 1`, or `val xs = List(1, 2, 3)` vs. `val xs: List[Int] = List[Int](1, 2, 3)`, or `val f = new File("SomeFile.txt")` vs. `val f: File = new File("SomeFile.txt")`. Function/class arguments always have to be typed, so _Scala_ will eventually get an opportunity to statically verify the type it has inferred. Personally, I would hate working in the straitjacket you're proposing. ;-) – Mike Allen May 31 '17 at 15:22
  • 1
    @MikeAllen Yep Agree with you Mike. There are few instances ; like the example you have given makes a lot of sense to not repeat type annotation multiple times and there are cases where providing an explicit annotation makes the code much easier to understand. Considering we are working as a team, I am looking for a way to bring some standard in our code development. I am just looking for a way where I can customize what needs explicit type annotation and what are not. – Raj May 31 '17 at 15:56

0 Answers0