Scala equivalent of C#’s extension methods?

前端 未结 5 1786
傲寒
傲寒 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:53

    Since version 2.10 of Scala, it is possible to make an entire class eligible for implicit conversion

    implicit class RichInt(i: Int) {
      def square = i * i
    }
    

    In addition, it is possible to avoid creating an instance of the extension type by having it extend AnyVal

    implicit class RichInt(val i: Int) extends AnyVal {
      def square = i * i
    }
    

    For more information on implicit classes and AnyVal, limitations and quirks, consult the official documentation:

    • http://docs.scala-lang.org/overviews/core/implicit-classes.html
    • http://docs.scala-lang.org/overviews/core/value-classes.html

提交回复
热议问题