开发者

Enhance Predefined Methods in Scala

开发者 https://www.devze.com 2022-12-29 05:59 出处:网络
Base question: Why can I write in Scala just: println(10) Why don\'t I need to write: Console println(10)

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 li开发者_高级运维ke "println"?


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消