3

I'm currently learning Scala, but there are still so much things I just don't understand...

So, I was randomly surfing some stack overflow when a wild answer appeared: https://stackoverflow.com/a/19093282/3529754

This answer makes use of an implicit parameter and the the foldLeft function with a - yes it looks like one - japanese smiley. the source code of question:

class Account(implicit transactionLog: TransactionLog) {
  def balance = transactionLog.foldLeft(_ + _)
}

class TransactionSlip(from: Account, to: Account, amount: BigDecimal)

What exactly does the implicit keyword mean in this case? What does the smiley do? I just don't get it from the snippets floating around...

Thanks in Advance.

Community
  • 1
  • 1
bash0r
  • 774
  • 6
  • 17

1 Answers1

4

Two answers:

  • _ + _ is a placeholder for the function that takes two arguments and adds them. The underscore is here to mark the position of an argument in such a syntax. You can read this for all the uses of underscore in Scala.

  • the implicit keyword denotes an implicit argument. It means in places where you require an Account, one may be provided using the constructor without explicitly giving the corresponding transactionLog, which will be grabbed from the context.

Francois G
  • 11,957
  • 54
  • 59
  • Thanks, that did what I needed to understand the code. – bash0r Nov 24 '14 at 14:37
  • If your just learning Scala I would say always ask about questions like this but don't worry too much about being able to write code like this immediately. This might be 'better' style etc but it is hard to think in implicits and underscores immediately.You can always get help on style and learn to write this but if it doesn't click yet that is ok in my opinion. – Barry Nov 24 '14 at 15:10
  • @Barry I'm coming from a functional background (e.g. Haskell and some not so successful trials of implementing higher-class types in C#...). The thinking is not so much of a problem rather than matching the syntax of Scala to the syntax of other languages I use to know. I love to think functional due to it's stylish shortness and elegance. :) – bash0r Nov 24 '14 at 15:14
  • @bashOr oh cool lately I have been working with a team doing java -> Scala and run into this a lot where too much time is spent on trying to write things perfectly/most compact way rather than get something working and then we can always help with style. – Barry Nov 24 '14 at 15:23
  • @Barry Oh yeah, my team is so frightened of functional programming, that they just don't even want to try. Even if the semantics a functional programming language brings in, they just want to struggle and fight with the problems of old school Java with all these null checks and crazy exceptions flying around... Error code that you could handle gracefully in a functional language... – bash0r Nov 24 '14 at 17:06