Refuse to call `get` on Option and generate a compilation error

If I want to generate a compile-time error when calling .get for any Option value, how to do this?

Didn't write any custom macros, but did they guess the time? Any pointers?

+6
source share
2 answers

There is a compiler plugin called wartremover that provides what you want. https://github.com/typelevel/wartremover

It contains error messages and warnings for some scala functions that should be avoided for security.

This is a description of the OptionPartial wart from the github readme page:

scala.Option has a get method that will scala.Option if the value is None . The program should be reorganized to use scala.Option#fold to explicitly handle both Some and None cases.

compiler plugin

To add wartremover as a plugin to scalac, you need to add it to your project/plugins.sbt :

 resolvers += Resolver.sonatypeRepo("releases") addSbtPlugin("org.brianmckenna" % "sbt-wartremover" % "0.11") 

And activate it in build.sbt :

 wartremoverErrors ++= Warts.unsafe 

Macro

https://github.com/typelevel/wartremover/blob/master/OTHER-WAYS.md describes other ways to use the plugin, one of which uses it as a macro, as mentioned in the question.

Add wart remover as a library to your build.sbt :

 resolvers += Resolver.sonatypeRepo("releases") libraryDependencies += "org.brianmckenna" %% "wartremover" % "0.11" 

You can make any wart in a macro, for example:

 scala> import language.experimental.macros import language.experimental.macros scala> import org.brianmckenna.wartremover.warts.Unsafe import org.brianmckenna.wartremover.warts.Unsafe scala> def safe(expr: Any):Any = macro Unsafe.asMacro safe: (expr: Any)Any scala> safe { 1.some.get } <console>:10: error: Option#get is disabled - use Option#fold instead safe { 1.some.get } 

Example adapted from github wartremover page.

+9
source

Not strictly the answer to your question, but you may prefer to use the Scalaz Maybe type, which avoids this problem without having a .get method.

+3
source

Source: https://habr.com/ru/post/976860/


All Articles