Combinators

92 views
Skip to first unread message

incognito....@gmail.com

unread,
Jan 31, 2015, 11:50:05 AM1/31/15
to scala-l...@googlegroups.com
I started reading Scala in Action as my first Scala book (I've come to realize this book is way too advanced for beginners, i am struggling mightily). 

I need help with the following. 

object Combinators {
  implicit def kestrel[A](a: A) = new {
    def tap(sideEffect: A => Unit): A = {
      sideEffect(a)
      a
    }
  }
}

case class Person(firstName: String, lastName: String)
case class Mailer(mailAddress: String) {
  def mail(body: String) = {
    println("send mail here...")
  }
}

object Main {
  import Combinators._
  def main(args: Array[String]): Unit = {
    Person("Nilanjan", "Raychaudhuri").tap(p => {
      println("First name " + p.firstName)
      Mailer("some address").mail("new person joined " + p)
    }).lastName
  }
}

My questions are as follows:
1) How does Person automatically get access to "tap"? 
 2) What does the implicit keyword do here? (am guessing this might answer q #1)
3) Any other book suggestions for a Java guy trying to learn Scala. (I've got about 10 years of Java experience, if that helps).

Thanks in advance. 

Vlad Patryshev

unread,
Jan 31, 2015, 11:56:59 AM1/31/15
to scala-l...@googlegroups.com
As I see, you will need to figure out how implicit works.
You can google it, or read some kind of introduction to Scala.

In short, it is implicit, and is applied when compiler finds it necessary.

Thanks,
-Vlad

--
You received this message because you are subscribed to the Google Groups "scala-language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-languag...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

incognito....@gmail.com

unread,
Jan 31, 2015, 11:59:46 AM1/31/15
to scala-l...@googlegroups.com
Also what is this line doing here?

  implicit def kestrel[A](a: A) = new {

What does "new" do in this context? a new function?

Simon Schäfer

unread,
Jan 31, 2015, 12:21:58 PM1/31/15
to scala-l...@googlegroups.com

On 01/31/2015 05:59 PM, incognito....@gmail.com wrote:
Also what is this line doing here?

  implicit def kestrel[A](a: A) = new {

What does "new" do in this context? a new function?
It represents an anonymous class, in short notation:

scala> new {}
res0: AnyRef = $anon$1@67424e82

scala> new Object {}
res1: Object = $anon$1@51521cc1

--

incognito....@gmail.com

unread,
Jan 31, 2015, 2:51:26 PM1/31/15
to scala-l...@googlegroups.com
Thanks all,
Reply all
Reply to author
Forward
0 new messages