Scala: Difference between revisions

From Celeste@Hoppinglife
Jump to navigation Jump to search
Created page with "=== Type bounds === <code>B <: U</code> imposes a ''upper bound'' on type <code>U</code>, while <code>B >: L</code> imposes a ''lower bound''. This is useful for generic meth..."
 
Line 4: Line 4:


The official tour has a pretty good explanation: [https://docs.scala-lang.org/tour/upper-type-bounds.html Upper bounds] and [https://docs.scala-lang.org/tour/lower-type-bounds.html Lower bounds]
The official tour has a pretty good explanation: [https://docs.scala-lang.org/tour/upper-type-bounds.html Upper bounds] and [https://docs.scala-lang.org/tour/lower-type-bounds.html Lower bounds]
=== Self Type ===
A trait with a self type cannot be used without mixed in that trait first.
<pre class="hljs scala">
trait User {
  def username: String
}
trait Tweeter {
  this: User =>  // reassign this
  def tweet(tweetText: String) = println(s"$username: $tweetText")
}
</pre>
A question is how it is different from trait subclasses.
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.

Revision as of 22:58, 26 May 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.

See Official tour, a discussion on the cake pattern and a StackOverflow question about this.