Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala equivalent of C#’s extension methods?

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?

like image 595
John Avatar asked Jun 25 '10 16:06

John


People also ask

What is r 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.

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 does _* mean in Scala?

: _* 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.

How do I create a static variable in Scala?

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.


1 Answers

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) } 
like image 196
Mitch Blevins Avatar answered Oct 04 '22 09:10

Mitch Blevins