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?
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