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:
Try
; Try[Unit]
in your case 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.