Scala equivalent of C#’s extension methods?

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

    This would be the code after Daniel's comment.

    object MyExtensions {
        class RichInt( i: Int ) {
            def square = i * i
        }
        implicit def richInt( i: Int ) = new RichInt( i )
    
        def main( args: Array[String] ) {
            println("The square of 2 is: " + 2.square )
        }
    }
    

提交回复
热议问题