복붙노트

[SCALA] C #의 확장 방법의 스칼라 동등한?

SCALA

C #의 확장 방법의 스칼라 동등한?

C #에서 당신은 쓸 수 있습니다 :

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

어떻게 것 스칼라처럼 간단한 확장 메서드 모양?

해결법

  1. ==============================

    1.포주 내 도서관 패턴은 유사한 구조입니다 :

    포주 내 도서관 패턴은 유사한 구조입니다 :

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

    @Daniel 스피 웍의 의견에 따라,이 성능을 돕고, 메소드 호출에 반사를 방지 할 수 있습니다 :

    object MyExtensions {
      class RichInt(i: Int) {
        def square = i * i
      }
      implicit def richInt(i: Int) = new RichInt(i)
    }
    
  2. ==============================

    2.스칼라 버전 2.10 때문에, 암시 적 변환에 대한 전체 클래스 자격을 할 수 있습니다

    스칼라 버전 2.10 때문에, 암시 적 변환에 대한 전체 클래스 자격을 할 수 있습니다

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

    또한, AnyVal 연장함으로써 확장자 유형의 인스턴스를 생성 회피 할 수있다

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

    암시 적 클래스와 AnyVal, 한계와 단점에 대한 자세한 내용은 공식 문서를 참조하십시오 :

  3. ==============================

    3.이것은 다니엘의 코멘트 이후의 코드가 될 것입니다.

    이것은 다니엘의 코멘트 이후의 코드가 될 것입니다.

    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 )
        }
    }
    
  4. ==============================

    4.당신이 문자열을 사용하는 경우 스칼라에서 우리는, 웹에서 찾을 아주 쉽게 많은 논의 포주 내 도서관 패턴, (언어의 발명자) 소위를 사용하고 (키워드되지 않음) 검색 할 수 있습니다.

    당신이 문자열을 사용하는 경우 스칼라에서 우리는, 웹에서 찾을 아주 쉽게 많은 논의 포주 내 도서관 패턴, (언어의 발명자) 소위를 사용하고 (키워드되지 않음) 검색 할 수 있습니다.

  5. from https://stackoverflow.com/questions/3119580/scala-equivalent-of-c-s-extension-methods by cc-by-sa and MIT license