kotlin에서 "instanceof"클래스를 확인하는 방법은 무엇입니까?
kotlin 클래스에서는 클래스 유형 T에 대한 메소드 매개 변수를 객체로 사용합니다 ( 여기 kotlin doc 참조 ) . 객체로서 메서드를 호출 할 때 다른 클래스를 전달하고 있습니다. Java에서는 어떤 클래스인지 객체를 사용하여 클래스를 비교할 수 있습니다 .instanceof
그래서 런타임에 어떤 클래스인지 확인하고 비교하고 싶습니다.
kotlin에서 instanceof 클래스를 어떻게 확인할 수 있습니까?
사용 is
.
if (myInstance is String) { ... }
또는 그 반대 !is
if (myInstance !is String) { ... }
결합 when
및 is
:
when (x) {
is Int -> print(x + 1)
is String -> print(x.length + 1)
is IntArray -> print(x.sum())
}
공식 문서 에서 복사
is
연산자 또는 부정 형식 을 사용하여 런타임에 객체가 주어진 유형을 따르는 지 확인할 수 있습니다 !is
.
예:
if (obj is String) {
print(obj.length)
}
if (obj !is String) {
print("Not a String")
}
사용자 정의 개체의 경우 또 다른 예 :
하자, obj
유형이 CustomObject
있습니다.
if (obj is CustomObject) {
print("obj is of type CustomObject")
}
if (obj !is CustomObject) {
print("obj is not of type CustomObject")
}
다음을 사용할 수 있습니다 is
.
class B
val a: A = A()
if (a is A) { /* do something */ }
when (a) {
someValue -> { /* do something */ }
is B -> { /* do something */ }
else -> { /* do something */ }
}
공식 페이지 참조 라는 키워드를 사용해보십시오is
if (obj is String) {
// obj is a String
}
if (obj !is String) {
// // obj is not a String
}
이렇게 확인할 수 있습니다
private var mActivity : Activity? = null
그때
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is MainActivity){
mActivity = context
}
}
기타 솔루션 : 코 틀린
val fragment = supportFragmentManager.findFragmentById(R.id.fragment_container)
if (fragment?.tag == "MyFragment")
{}
https://kotlinlang.org/docs/reference/typecasts.html에서 Kotlin 문서를 읽을 수 있습니다 . 우리는를 사용하여 런타임에서 특정 타입인지 오브젝트 따르는 것으로 확인할 수 is
운영자 또는 부정 형상을 !is
사용하여, 예를 들어 is
:
fun <T> getResult(args: T): Int {
if (args is String){ //check if argumen is String
return args.toString().length
}else if (args is Int){ //check if argumen is int
return args.hashCode().times(5)
}
return 0
}
그런 다음 주요 기능에서 인쇄하여 터미널에 표시하려고합니다.
fun main() {
val stringResult = getResult("Kotlin")
val intResult = getResult(100)
// TODO 2
println(stringResult)
println(intResult)
}
이것은 출력입니다
6
500
참고 URL : https://stackoverflow.com/questions/44098780/how-to-check-instanceof-class-in-kotlin
'Development Tip' 카테고리의 다른 글
HTML 양식에서 Flask의 Python 스크립트로 데이터 보내기 (0) | 2020.12.06 |
---|---|
화면의 백분율로 설정된 DIV 높이? (0) | 2020.12.06 |
경과 시간 계산 (0) | 2020.12.06 |
C ++ std :: vector에서 모든 항목 삭제 (0) | 2020.12.06 |
document.getElementById를 사용하여 iframe 내부의 요소를 선택하는 방법 (0) | 2020.12.06 |