Scala "Sentence-Like" Function Definition

151 views Asked by At

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.

1

There are 1 answers

2
Angelo Genovese On BEST ANSWER

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("?")

}