Scala equivalent of C#’s extension methods?

前端 未结 5 1767
傲寒
傲寒 2020-12-07 12:09

In C# you can write:

using System.Numerics;
namespace ExtensionTest {
public static class MyExtensions {
    public static BigInteger Square(this BigInteger          


        
5条回答
  •  [愿得一人]
    2020-12-07 12:48

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

提交回复
热议问题