Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enhance Predefined Methods in Scala

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

like image 490
fratnk Avatar asked May 04 '10 10:05

fratnk


People also ask

What does ++ mean in Scala?

Since ++ generally represents concatenation of two collections, ++= would mean an "in place" update of a collection with another collection by concatenating the second collection to the first.

What is the meaning of => in Scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .

What is the syntax of defining method in Scala?

Scala doesn't allow us to define an anonymous method. We have to use a special keyword def for method definition: def inc(number: Int): Int = number + 1. We can define a method's list of parameters in parentheses after its name.


1 Answers

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

like image 180
Jesper Avatar answered Sep 25 '22 19:09

Jesper