반응형
Kotlin에서 익명 인터페이스의 인스턴스를 만드는 방법은 무엇입니까?
다음과 같은 인터페이스를 가진 객체 인 타사 Java 라이브러리가 있습니다.
public interface Handler<C> {
void call(C context) throws Exception;
}
다음과 같이 Java 익명 클래스와 유사한 Kotlin에서 어떻게 간결하게 구현할 수 있습니까?
Handler<MyContext> handler = new Handler<MyContext> {
@Override
public void call(MyContext context) throws Exception {
System.out.println("Hello world");
}
}
handler.call(myContext) // Prints "Hello world"
인터페이스에 SAM 을 사용할 수있는 단일 방법 만 있다고 가정합니다.
val handler = Handler<String> { println("Hello: $it")}
핸들러를 받아들이는 메소드가 있다면 타입 인수를 생략 할 수도 있습니다.
fun acceptHandler(handler:Handler<String>){}
acceptHandler(Handler { println("Hello: $it")})
acceptHandler({ println("Hello: $it")})
acceptHandler { println("Hello: $it")}
인터페이스에 둘 이상의 메소드가있는 경우 구문이 좀 더 장황합니다.
val handler = object: Handler2<String> {
override fun call(context: String?) { println("Call: $context") }
override fun run(context: String?) { println("Run: $context") }
}
var를 만들지 않고 인라인으로 수행하는 경우가 있습니다. 내가 그것을 달성 한 방법은
funA(object: InterfaceListener {
override fun OnMethod1() {}
override fun OnMethod2() {}
override fun OnPermissionsDeniedForever() {}
})
val obj = object : MyInterface {
override fun function1(arg:Int) { ... }
override fun function12(arg:Int,arg:Int) { ... }
}
가장 간단한 대답은 아마도 Kotlin의 람다 일 것입니다.
val handler = Handler<MyContext> {
println("Hello world")
}
handler.call(myContext) // Prints "Hello world"
반응형
'Nice programing' 카테고리의 다른 글
dplyr 조건부 값으로 변경 (0) | 2020.11.24 |
---|---|
Docker 이미지 필터를 사용하는 방법 (0) | 2020.11.24 |
WebKit / Safari 용 콘솔 API는 어디에 있습니까? (0) | 2020.11.24 |
IDE를 사용할 때 Powershell에서 타사 실행 파일을 호출 할 때 오류 발생 (0) | 2020.11.24 |
Symfony 2 WebTestCase에서 테스트 데이터베이스를 만들고 픽스쳐를로드하는 가장 좋은 방법은 무엇입니까? (0) | 2020.11.24 |