2016-10-05 6 views
1

를 호출하지합니다 String.unary_-에 대한 호출을 삽입하는 대신 범위의 메서드를 호출합니까?스칼라 어떻게이 코드가 단항 방법을

+0

이 this' (뭔가로 변환'에 암시 적 변환을 얻기 위해'this.f (ARG) '로이 필요한 이유에 대한 문제있다 'f'로), 왜 f (arg) 충분하지 않은가? 이것은 좋은 예가 될 수 있습니다. 아니면, 실패하기 전에'this.expr'을 시험해보기위한 인자 일 수도 있습니다. –

답변

1
val foo = this.+("hello") //this will call the class, object etc. and you will get the correct reference for the method :) 

또는 :

import <path>._ 

val foo = classname.+("hello") 

또는 :

import <path>.<class> 

val foo = <class>.+("hello") 

예 :

package test 

object SO { 

    def +(s:String) = s.headOption 

} 

package test 

object add extends App { 
    import test.SO 

    println(SO.+("hello")) 
} 

해상도 :

Some(h) 

EX2 :

package test 

class SO {} 
object SO { 
    def apply(): SO = { 
     new SO 
    } 
    def +(s:String) = s.headOption 
} 



package test 

object add extends App { 
    import test.SO 

    println(SO.+("string")) 
} 

해상도 :

Some(s) 
+0

시도해 보셨습니까? – Dima

+0

메소드를 가져올 때 이것은 작동하지 않습니다 –

+0

@Dima 예 그리고 작동합니다 – Jonatan