he Scala compiler won’t force you. In cases where you think you should
catch the exception, don’t rethrow the exception from Scala. It’s a bad practice.
A better way is to create an instance of the Either or Option type.
1
2
3
4
5
6
7
8
9
defwrite(content: String): Either[Exception, Boolean] = {
val w = new Writer
try {
w.writeToFile(content)
Right(true)
} catch {
case e: java.io.IOException => Left(e)
}
}
Working with Java generics using existential types
Vector<?> could be represented as Vector[T] forSome { type T }
in Scala. Reading from left to right, this type
expression represents a vector of T for some type of T .
This type T is unknown and could be anything.
But T is fixed to some type for this vector.
There’s placeholder syntax for existential type JVector[_]. It means the same
thing as JVector[T] forSome { type T }. The preceding printLanguages method
could also be written as follows:
JavaConversions provides a series of implicit conversions that convert
between a Java collection and the closest corresponding Scala collection, and vice
versa. JavaConverters uses a “Pimp my Library” pattern to add the asScala
method to Java collection and asJava method to Scala collection types.
My recommendation would be to use JavaConverters because it makes the conversion
explicit.