1

If I remove the parentheses from below to read printFn hc I get an error. I thought in Scala one parameter functions don't need the parens?

case class HelloClass(arg1:String)


object HelloWorld extends App {
  var hc = HelloClass("Hello World")
  printFn(hc)

  def printFn(a1:HelloClass) : Unit = {
    println(a1 arg1) /* or a1.arg1 */
  }
}
Ivan
  • 7,448
  • 14
  • 69
  • 134

2 Answers2

4

I think you mixed it up with the infix method notation. In Scala you can write either obj.method(argument) or obj method argument.

To apply this to your example, you need the "obj" part of the expression, so if you want to avoid parenthesis, you can write

this printFn hc

See also "When to use parenthesis in Scala infix notation".

Community
  • 1
  • 1
laughedelic
  • 6,230
  • 1
  • 32
  • 41
1

I Would like to add something about postfix as another answer covered about infix.Copied from Programming Scala

So, 1 + 2 is the same as 1.+(2), because of the “infix” notation where we can drop the period and parentheses for single-argument methods.1 Similarly, a method with no arguments can be invoked without the period. This is called “postfix” notation. However, use of this postfix convention can sometimes be confusing, so Scala 2.10 made it an optional feature.

Example for Postfix

1 toString

Example for Infix

private def testMethod(arg1: String): String = {
    arg1
  }
//this specifies current instance
println(this testMethod "Hello Scala")
Balaji Reddy
  • 5,576
  • 3
  • 36
  • 47