Home > Net >  How to allow @throws for case classes in Scala?
How to allow @throws for case classes in Scala?

Time:04-06

I have legacy Scala code to upgrade from 2.13.3 version to 2.13.8 version. During the upgrade, I am facing the following error:

On line 2: error: `@throws` only allowed for methods and constructors

The error is occurring due to @throws not allowed for case class. The code is as follows:

scala> @throws[IllegalArgumentException]
     | final case class MyClass(name: String, age: Int)
       final case class MyClass(name: String, age: Int)
                        ^
On line 2: error: `@throws` only allowed for methods and constructors

Hence, how can I allow @throws for case class in Scala 2.13.8.

CodePudding user response:

This seems to work in my 2.13 REPL:

scala
Welcome to Scala 2.13.8 (OpenJDK 64-Bit Server VM, Java 11.0.15).
Type in expressions for evaluation. Or try :help.

scala> final case class MyClass @throws(classOf[IllegalArgumentException]) (name: String, age: Int)
class MyClass

For anyone else that's curious, this behavior seems to have changed in 2.13.5: https://github.com/scala/scala/pull/9465

  • Related