简体   繁体   中英

How to type a function in scala that may throw an exception?

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?

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() } 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM