1

I am refactoring some code and wanted to learn how Scala methods are written so that they can be written like:

foo = Map("Hello" -> 1)
foo contains "Hello"

where "contains" is the style I am looking to emulate. Here is the code I am refactoring (from exercism.io):

class Bob {
  def hey(statement:String): String = statement match {
    case x if isSilent(x)  => "Fine. Be that way!"
    case x if shouting(x) => "Whoa, chill out!"
    case x if asking(x) => "Sure."
    case _ => "Whatever."
  }

  def isSilent2:String => Boolean = _.trim.isEmpty

  def isSilent (str:String) = str.trim.isEmpty

  def shouting(str:String): Boolean = str.toUpperCase == str && str.toLowerCase != str

  def asking(str:String): Boolean = str.endsWith("?")

}

Ideally, I'd like to make my isSilent, shouting, and asking functions all able to be written in that style so that I can write:

case x if isSilent x => ...

Thanks for your help! Additionally, knowing what this is called in Scala (and other functional languages, because I think Haskell has something similar) would be really helpful as I've done quite a bit of searching and couldn't find what I was trying to describe.

lmcphers
  • 468
  • 3
  • 18

1 Answers1

2

This is referred to as Infix Notation and it doesn't require anything special so long as you have a single argument function.

The reason it isn't working for you is that you need the object whose method is being called. The following compiles:

class Bob {
  def hey(statement:String): String = statement match {
    case x if this isSilent x  => "Fine. Be that way!"
    case x if this shouting x  => "Whoa, chill out!"
    case x if this asking x => "Sure."
    case _ => "Whatever."
  }

  def isSilent2:String => Boolean = _.trim.isEmpty

  def isSilent (str:String) = str.trim.isEmpty

  def shouting(str:String): Boolean = str.toUpperCase == str && str.toLowerCase != str

  def asking(str:String): Boolean = str.endsWith("?")

}
Angelo Genovese
  • 3,398
  • 17
  • 23
  • Wow! What a simple fix. So much searching work for such a simple solution, blech! Thank you so much Angelo. – lmcphers Jun 11 '15 at 19:22
  • 1
    You're very welcome, but generally "thank you" comments are discouraged on SO :) http://meta.stackexchange.com/questions/126180/is-it-acceptable-to-write-a-thank-you-in-a-comment – Angelo Genovese Jun 11 '15 at 19:24