0

I like to indicate that a function might throw an exception. Currently, I have a few validation functions in the form of:

val throwUnlessX: String => Unit = (foo: String) => {
  if (foo != "bar") {
    throw new Throwable("Poit!")
  }
}

It's typed with Unit as a return type, yet strictly speaking that's not entirely correct as the function may also never return as it may throw an exception instead.

Other languages have the concept of defining a never type, either for infinite loops or said exception throwing.

Is there something I can do to indicate to a developer that a function might throw or never returns?

k0pernikus
  • 60,309
  • 67
  • 216
  • 347

2 Answers2

1

You can use @throws annotation to declare the exception that can be thrown by a method.

Showcased example:

class Reader(fname: String) {
  private val in = new BufferedReader(new FileReader(fname))
  @throws[IOException]("if the file doesn't exist")
  def read() = in.read()
}
k0pernikus
  • 60,309
  • 67
  • 216
  • 347
Artavazd Balayan
  • 2,353
  • 1
  • 16
  • 25
0

There are types to represent these cases in Scala:

  • a type can capture the notion of exception with Try; Try[Unit] in your case
  • if you ascribe a type that has no instance as a return type, that will indicate that the function never returns, like Nothing

However, I strongly suggest the use of some validation library to your use case that does not throw exceptions; a good candidate would be Scalaz for example.

mpetruska
  • 633
  • 3
  • 6
  • Could you please expand the example for the `try` case? It seems that I then have to use Failure and Success, yet I don't know how to say: this is the success case, return with the success Unit. – k0pernikus Apr 10 '18 at 09:59
  • Follow up to my comment: I was looking for `Success(())`. – k0pernikus Apr 10 '18 at 10:15
  • In addition to `Try`, `Either` is a good option. `Try` has the disadvantage of hiding the exception type, with either you can identify the specific exception that might be thrown, or even use a non-exception type as the error case. – puhlen Apr 10 '18 at 14:47
  • Sorry for the late reply: I think you should use a validation framework. You can find [Try](http://www.scala-lang.org/api/current/scala/util/Try.html) and [Either](http://www.scala-lang.org/api/current/scala/util/Either.html) in the documentation. – mpetruska Apr 11 '18 at 09:32
  • The reply above is for the original question: how to represent exceptions and never returning functions with the type system of Scala. Was it not your intention to ask that? – mpetruska Apr 11 '18 at 09:33