Eugene Loy
Eugene Loy

Reputation: 12416

Is it possible to annotate lambda in scala?

For my dsl I need something in the spirit of:

@deprecated def foo(x: Int) = x

... only for lambdas\anonymous functions.

Is something like this possible?

Upvotes: 1

Views: 197

Answers (1)

yǝsʞǝla
yǝsʞǝla

Reputation: 16412

Apparently this exists in the language according to the lang spec:

An annotation of an expression e appears after the expression e, separated by a colon.

So this supposed to work:

object TestAnnotation {
  val o = Some(1)

  def f = o.map(_ + 1 : @deprecated("gone", "forever"))

  val e = { 1 + 2 } : @deprecated("hmm", "y")

  println(f)
  println(e)
}

However, when I compile it with scalac -deprecation I get no warnings whatsoever. I opened an issue here and got a response that it's not supported.

One workaround you could use is to declare lambda separately:

object TestAnnotation {
  val o = Some(1)

  @deprecated("this", "works") val deprecatedLambda: Int => Int = _ + 1

  o.map(deprecatedLambda)
}

scalac then gives:

Annotation.scala:6: warning: value deprecatedLambda in object TestAnnotation is deprecated: this
  o.map(deprecatedLambda)
        ^
one warning found

Upvotes: 1

Related Questions