Scala: Difference between revisions

Jump to navigation Jump to search
 
(4 intermediate revisions by the same user not shown)
Line 8: Line 8:


A trait with a self type cannot be used without mixed in that trait first.  
A trait with a self type cannot be used without mixed in that trait first.  
<pre class="hljs scala">
 
<syntaxhighlight lang="scala">
trait User {
trait User {
   def username: String
   def username: String
Line 17: Line 18:
   def tweet(tweetText: String) = println(s"$username: $tweetText")
   def tweet(tweetText: String) = println(s"$username: $tweetText")
}
}
</pre>
</syntaxhighlight>


A question is how it is different from trait subclasses.
A question is how it is different from trait subclasses.
=== Context Bound ===


See [https://docs.scala-lang.org/tour/self-types.html Official tour], [http://jonasboner.com/real-world-scala-dependency-injection-di/ a discussion on the cake pattern] and [https://stackoverflow.com/questions/1990948/what-is-the-difference-between-self-types-and-trait-subclasses a StackOverflow question] about this.
See [https://docs.scala-lang.org/tour/self-types.html Official tour], [http://jonasboner.com/real-world-scala-dependency-injection-di/ a discussion on the cake pattern] and [https://stackoverflow.com/questions/1990948/what-is-the-difference-between-self-types-and-trait-subclasses 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
<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 [https://github.com/jsuereth/scala-arm scala-arm].