I am new to Scala. What are the differences (and similarities) between "frog" and "phil" in the following two expressions? What does the second one ("phil") do precisely?
scala> val frog = new Frog frog: Frog = green scala> val phil: Philosophical = frog phil: Philosophical = green
This example is from Odersky et al. (2010, p. 259); see image below.
The declaration of
phil is just a declaration that restricts you to treating
phil as a
Philosopher (i.e. you can only use it in places that expect a
Philosopher or a supertype of
Philosopher). You can do this with a
Frog as well (thanks to
extends Philosopher; that the compiler let you declare
phil is only because a
Frog is always a
Philosopher). So there's no practical purpose to that declaration.
In the context of the book, it just illustrates that you can treat a trait as its own type. Most notably, this means you can define functions and methods that take and result in objects implementing a particular trait (as well as define collections of objects implementing a particular trait).