On Sun, Jun 3, 2012 at 1:30 AM, James Ong <
yanli...@gmail.com> wrote:
> Have a few syntax which I'm not clear without a clear explanation in
> layman term:
>
> What is Implicit? Similar to type casting or "just convert it to this
> type and don't care what members is of different type"?
Well, neither. You are probably thinking of "implicit conversions",
which is just one way of using implicits. So, let me try to be a bit
more formal here:
* An "implicit parameter" is a parameter that, if not passed
explicitly at the call site, will be looked for by the compiler in
some places and, if found, passed on by the compiler itself.
* An "implicit declaration" is simply a way of telling the compiler
about some parameter one wants to be passed implicitly.
Very simple example:
def f(implicit n: Int) = n * 2
implicit val x = 2
println(f(3)) // prints 6
println(f) // prints 4
Now, an "implicit conversion" is an implicit of the type "A => B",
that is, a function from type A to type B. As any implicit, it may
appear both as a parameter and as a declaration. However, implicit
conversions have an additional meaning to the compiler. If an implicit
conversion A => B can be found (that is, the compiler can find a
declaration of an implicit function A => B), then one may call methods
declared solely on B on an object of type A. For example:
class B(n: Int) { def squared = n * n }
implicit def g(n: Int): B = new B(n)
println(2 .squared) // the space is there so that the compiler doesn't
think we are talking about the Double "2."
And, to be very clear about it, it is not a cast.
> What does => mean?
It depends on the context. It can either declare a function type, or
be used in a function literal. For example:
type MyFunc = Int => Int // MyFunc is a function taking an Int
parameter and returning an Int result
val h: MyFunc = x => x * 2 // h is a function that takes an x
parameter and returns x * 2
println(h(2)) // prints 4
There are other contexts in which "=>" may appear. Right now I
remember "case cond => stmts", where "=>" separated the condition from
the statements to be executed if the condition is true. It might have
other uses I don't recall at the moment. If you are not clear, please
show the code that is confusing you.
> How do I explain clear on this part (_+_)
"_" in this particular context is a placeholder for anonymous
parameters in an anonymous function. Please note that "_" has a dozen
other meanings, which I won't bother to discuss.
In this particular case, "(_+_)" is equivalent to "(x$1, x$2) => x$1 +
x$2", that is, a function literal that takes two parameters and return
the addition of them. For example:
val i: (Int, Int) => Int = (_+_)
println(i(1,1)) // prints 2
You can find a number of explanations related to these concepts at the
FAQ on the
docs.scala-lang.org site. The FAQ is sadly hidden under
"Tutorials".
--
Daniel C. Sobral
I travel to the future all the time.