In C# you can write:
using System.Numerics; namespace ExtensionTest { public static class MyExtensions { public static BigInteger Square(this BigInteger n) { return n * n; } static void Main(string[] args) { BigInteger two = new BigInteger(2); System.Console.WriteLine("The square of 2 is " + two.Square()); } }}
How would this simple extension method look like in Scala?
R is a scripting language and environment developed by statisticians for statistical computing and graphics. Like Scala, R supports a functional programming style and provides immutable data types. Scala programmers who learn R will find many familiar concepts, despite the syntactical differences.
=> 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 .
: _* is a special instance of type ascription which tells the compiler to treat a single argument of a sequence type as a variable argument sequence, i.e. varargs. It is completely valid to create a Queue using Queue.
There are no static variables in Scala. Fields are variables that belong to an object. The fields are accessible from inside every method in the object. Fields can also be accessible outside the object, depending on what access modifiers the field is declared with.
The Pimp My Library pattern is the analogous construction:
object MyExtensions { implicit def richInt(i: Int) = new { def square = i * i } } object App extends Application { import MyExtensions._ val two = 2 println("The square of 2 is " + two.square) }
Per @Daniel Spiewak's comments, this will avoid reflection on method invocation, aiding performance:
object MyExtensions { class RichInt(i: Int) { def square = i * i } implicit def richInt(i: Int) = new RichInt(i) }
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