2012-11-13 2 views
10

이 같은 객체의 이름을 수 있지만, m를 호출 할 수 없습니다 : 개체 +가있는 스칼라의 중절 표기법은 왜 가능하지 않습니까?

object + { 
    def m (s: String) = println(s) 
} 

+.m("hi")를 호출 할 수 없습니다 :
<console>:1: error: illegal start of simple expression 
     +.m("hi") 

는 또한 + m "hi"를 호출 할 수 없습니다 (DSL-사용을 위해 선호).

그러나 object ++으로 제대로 작동합니다. 그들은 (존재하지 않는) unary_+ 메서드와 충돌합니까? 이것을 피할 수 있습니까?

+1

난 이유에서 추측보다 더 나은 아무것도 없어 +는 사용할 수 없지만'$ plus.m ("hi")' – Austin

답변

11

실제로 단항 연산자를 사용할 수 없습니다. 당신은 어쨌든 그것을 호출 할 경우 (달러로 시작) JVM에 대해 컴파일러에 의해 생성 된 이름을 사용에 의존 수 :

scala> object + { 
    | def m(s: String) = println(s) 
    | } 
defined module $plus 

scala> +.m("hello") 
<console>:1: error: illegal start of simple expression 
     +.m("hello") 
     ^

scala> $plus.m("hello") 
hello 
6

내가 믿는 문제는없이 단항 연산자를 처리하기 위해 모호성, 스칼라는 특별한 경우에 의존합니다. !, +, -~은 단항 연산자로 취급됩니다. 따라서 +.m("hi")에서 scala는 단항 연산자로 +을 처리하며 전체 표현식을 이해할 수 없습니다.

1

또 다른 코드를 사용하여 패키지

object Operator extends App { 
    // http://stackoverflow.com/questions/13367122/scalas-infix-notation-with-object-why-not-possible 
    pkg1.Sample.f 
    pkg2.Sample.f 
} 

package pkg1 { 
    object + { 
     def m (s: String) = println(s) 
    } 

    object Sample { 
     def f = { 
      // +.m("hi") => compile error: illegal start of simple expression 
      // + m "hi" => compile error: expected but string literal found. 
      $plus.m("hi pkg1") 
      $plus m "hi pkg1" 
     } 
    } 
} 

package pkg2 { 
    object + { 
     def m (s: String) = println(s) 
    } 

    object Sample { 
     def f = { 
      pkg2.+.m("hi pkg2") 
      pkg2.+ m "hi pkg2" 
      pkg2.$plus.m("hi pkg2") 
      pkg2.$plus m "hi pkg2" 
     } 
    } 
} 

자바 버전 "1.7.0_09는"불행하게도

스칼라 코드 주자 버전 2.9.2

관련 문제