views:

157

answers:

1

Base question:

Why can I write in Scala just:

println(10)

Why don't I need to write:

Console println(10)

Followup question:

How can I introduce a new method "foo" which is everywhere visible and usable like "println"?

+15  A: 

You don't need to write the Console in front of the statement because the Scala Predef object, which is automatically imported for any Scala source file, contains definitions like these:

def println() = Console.println()
def println(x: Any) = Console.println(x)

You cannot easily create a "global" method that's automatically visible everywhere yourself. What you can do is put such methods in a package object, for example:

package something

package object mypackage {
    def foo(name: String): Unit = println("Hello " + name")
}

But to be able to use it, you'd need to import the package:

import something.mypackage._

object MyProgram {
    def main(args: Array[String]): Unit = {
        foo("World")
    }
}

(Note: Instead of a package object you could also put it in a regular object, class or trait, as long as you import the content of the object, class or trait - but package objects are more or less meant for this purpose).

Jesper
Thanks. Almost perfect answer. Is there a possibility to avoid the import? I mean: Can I enhance this "Predef" Object?
fratnk
Package object is automatically imported in all the classes and objects in that package.
missingfaktor
@fratnk: About using StackOverflow: You can click the check mark at the top left of my post to accept it as the answer for your question.
Jesper
The `Predef` object is in the Scala library, you don't want to be hacking your own code in there - so you can't add your own things to the `Predef` object.
Jesper