Scala: Difference between revisions
Hoppinglife (talk | contribs) |
Hoppinglife (talk | contribs) |
||
| Line 31: | Line 31: | ||
<code>finalize()</code> method in <code>Object</code>, but introduced [https://stackoverflow.com/questions/56139760/why-is-the-finalize-method-deprecated-in-java-9 problems] and were deprecated. Java classes holding non-heap resources should provide a close method, as well as lean on [https://docs.oracle.com/javase/9/docs/api/java/lang/ref/Cleaner.html Cleaner] and [https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html Autoclosable] to implement safe resource release. | <code>finalize()</code> method in <code>Object</code>, but introduced [https://stackoverflow.com/questions/56139760/why-is-the-finalize-method-deprecated-in-java-9 problems] and were deprecated. Java classes holding non-heap resources should provide a close method, as well as lean on [https://docs.oracle.com/javase/9/docs/api/java/lang/ref/Cleaner.html Cleaner] and [https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html Autoclosable] to implement safe resource release. | ||
For Scala, the best resource-management mechanism seems to be a library [ | For Scala, the best resource-management mechanism seems to be a library [https://github.com/jsuereth/scala-arm scala-arm]. | ||
Latest revision as of 19:31, 14 June 2020
Type bounds
B <: U imposes a upper bound on type U, while B >: L imposes a lower bound. This is useful for generic methods that takes only classes on a particular inheritance tree as its type parameters.
The official tour has a pretty good explanation: Upper bounds and Lower bounds
Self Type
A trait with a self type cannot be used without mixed in that trait first.
trait User {
def username: String
}
trait Tweeter {
this: User => // reassign this
def tweet(tweetText: String) = println(s"$username: $tweetText")
}
A question is how it is different from trait subclasses.
Context Bound
See Official tour, a discussion on the cake pattern and a StackOverflow question about this.
RAII and Resource Handling
Java and Scala do not have deterministic destructors due to automatic garbage collection. Java has a
finalize() method in Object, but introduced problems and were deprecated. Java classes holding non-heap resources should provide a close method, as well as lean on Cleaner and Autoclosable to implement safe resource release.
For Scala, the best resource-management mechanism seems to be a library scala-arm.