Remove Scala warts with WartRemover

Each time we write code, we are told to ‘maintain the coding standards’, yet many a time we fail to do so. Though there are tools which we use to help us in linting the code like scalastyle, scapegoat, scalafmt, scalariform etc. lack a bit, seems not enough to meet the standard. Basically though we use all these tools still there is wart and therefore there comes WartRemover to rescue us from these warts.

Now the question comes, What’s WartRemover ?

Well, WartRemover is a flexible Scala code linting tool. It takes the pain out of writing scala by removing some of the language’s nastier features. It works with the type system to improve the reliability of your code.

Different ways of using WartRemover

  • Using the sbt plugin
  • As a command-line tool
  • As a compiler plugin with manually provided scalac options
  • To derive macros

It catches the following issues:

  • Inference issues
    • Type inferred as Any
    • Type inferred as Nothing
    • Type inferred as Product
    • Type inferred as Serializable
  • Runtime type coercion
    • asInstanceOf
    • isInstanceOf
    • use of any2stringadd
  • Partial methods and type-safety breaking features
    • Use of List: head, tail, last
    • Use of Option.get
    • Use of LeftProjection.get
    • Use of RightProjection.get
    • Use of null
  • Patterns that damage reuse/reasoning
    • Use of var
    • Use of return
    • Statements that return non-Unit values
    • Functions taking default arguments

Oof… isn’t it a big list, however apparently it will truly rescue us from the warts and it is as simple as it sounds. Now let’s try this with an example. Open your sbt project and follow the steps given below:

1) Add the following to your project/plugins.sbt:

(NOTE: sbt-wartremover requires sbt version 0.13.5+)

2) Add the following to build.sbt:

3) Now write any code violating coding standards, say for example:

4) Now run, sbt compile. It will show the warnings for the above scala warts like below –

Screenshot from 2017-06-15 11-21-50

So, this is just for one of the violations we do. There’s a long list of built-in warts it checks for. You can explore for that from this link.
Write more, worry less. Happy coding 🙂

References:

  1. http://www.wartremover.org/
  2. https://queertypes.com/posts/33-scala-wart-remover.html

KNOLDUS-advt-sticker

Written by 

Ramandeep Kaur is a Software Consultant, having experience of more than 1.5 years. She is a Java enthusiast and has knowledge of languages like C, C++, C#, and Scala. She is familiar with Object Oriented Programming Paradigms and also has a great interest in relational database technologies. Her hobbies include reading novels and listening music.

Leave a Reply

%d bloggers like this: