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)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With