Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala "is not a member of" when chaining method calls without periods and parameters

Tags:

scala

Continuation of my work in: Scala "does not take parameters" when chaining method calls without periods

Given the accepted answer, this time I want to pass a parameter to one of the methods.

Original suggestion:

object and

class Greeter {
  def hi(a: and.type) = { print("hi"); this }
  def hello = { print("hello"); this }
}

new Greeter hi and hello

My new code:

object and

class Greeter {
  def hi(name: String) = { print("hi" + name); this }
  def hi(name: String, a: and.type): Greeter = hi(name)
  def hello = { print("hello"); this }
}

but when I: new Greeter hi "Miguel" and

I get: error: value and is not a member of Greeter

putting the parentheses and comma works: new Greeter hi ("Miguel", and)

like image 249
mparaz Avatar asked Jan 25 '26 02:01

mparaz


2 Answers

In Scala, there must always be parentheses around a parameter list with more than one parameter. Leaving those off is simply not possible.

new Greeter hi "Miguel" and is interpreted as (new Greeter).hi("Miguel").and, i.e. it's trying to invoke an and method on a Greeter object.

like image 90
Knut Arne Vedaa Avatar answered Jan 28 '26 13:01

Knut Arne Vedaa


The compiler isn't always able to infer parantheses. My rule is simply that if it blows up without them I add them and move on. Usually, I'll later learn the language further and then come back and clean up my code in ways that removes them (if they are part of a DSL). But, i've found trying to do so upfront takes 20 times longer to find an answer. Could've released the software much sooner if I just accepted a couple mild blemishes.

like image 28
Dante Romero Avatar answered Jan 28 '26 11:01

Dante Romero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!