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"?
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.
=> 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 .
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With