Reputation: 729
I'm currently learning method chaining. I've provided a working python example.
#!/bin/python3
import sys
class Generator(object):
def __init__(self):
return None
def echo(self, myStr):
sys.stdout.write(myStr)
return self
g = Generator()
g.echo("Hello, ").echo("World!\n")
But the Scala version doesn't seem to work, no text is being output.
#!/usr/bin/env scala
final class Printer() {
def echo(msg: String): this.type = {
println(msg)
this
}
}
class Driver {
def main(args: Array[String]) {
var pr = new Printer();
pr.echo("Hello, ").echo("World!")
}
}
Does anybody know why the scala version is not working and why?
Upvotes: 0
Views: 1521
Reputation: 25779
You need to compile and call your scala bytecode aferwards. Also, you don't need to specify this.type
if your Printer
is final
, e.g. if your driver.scala
file contains:
final class Printer() {
def echo(msg: String) = {
println(msg)
this
}
}
object Driver {
def main(args: Array[String]) {
var pr = new Printer();
pr.echo("Hello, ").echo("World!")
}
}
Then just call:
scalac driver.scala
scala Driver
Upvotes: 3
Reputation: 49
You should call the main method in your script.
new Driver().main(...)
should solve your problem.
Besides, it is the norm to define a main method in an object.
So, instead of
class Driver {
def main(args: Array[String]) {
var pr = new Printer();
pr.echo("Hello, ").echo("World!")
}
}
new Driver().main(...)
I would recommend the following.
object Driver {
def main(args: Array[String]) {
var pr = new Printer();
pr.echo("Hello, ").echo("World!")
}
}
Driver.main(...)
Good luck!
Upvotes: 0