[android : kotlin] 코틀린 Unit 오브젝트 사용방법 & 사용 예시
Unit 키워드는 자바의 void에 해당된다.

Unit 클래스를 살펴보면 싱클턴 클래스 라는 것을 알 수 있다. 싱글턴이란?
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin
/**
* The type with only one value: the `Unit` object. This type corresponds to the `void` type in Java.
*/
public object Unit {
override fun toString() = "kotlin.Unit"
}
다음에 보는 예제 코드 처럼 3가지 유형으로 사용이 가능하다. return문만 선언하여 사용하는 경우, 리턴 키워드 뒤에 Unit을 리턴한 경우, 리턴문을 생략한 경우이다.
fun rtnUnit(): Unit {
println("call rtnUnit()")
return
}
fun rtnUnit2(): Unit {
println("call rtnUnit2()")
return Unit
}
fun rtnUnit3(): Unit {
println("call rtnUnit3()")
}
fun main (args: Array<String>) {
rtnUnit()
rtnUnit2()
rtnUnit3()
}
hashCode()메서드를 사용하여 리턴 결과를 확인해보니 동일한 객체(싱글톤)로 확인이 되었다.
fun rtnUnit(): Unit {
println("call rtnUnit()")
return
}
fun rtnUnit2(): Unit {
println("call rtnUnit2()")
return Unit
}
fun rtnUnit3(): Unit {
println("call rtnUnit3()")
}
fun main (args: Array<String>) {
println(rtnUnit().hashCode())
println(rtnUnit2().hashCode())
println(rtnUnit2().hashCode())
}
[출력결과] : 해시코드값이 746292446으로 동일하다. 즉 같은 객체이다.
call rtnUnit() 746292446 call rtnUnit2() 746292446 call rtnUnit2() 746292446
메서드를 생성시 리턴타입을 Unit으로 지정한 경우 리턴값이 존재하면 오류가 발생된다.
//리턴값이 있으면 오류가 발생된다.
//(The integer literal does not conform to the expected type Unit)
fun rtnUnit4(): Unit {
println("call rtnUnit4()")
return 1
}
fun rtnUnit4(): Unit {
println("call rtnUnit4()")
return ""
}

[REFERENCE]
kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/#unit
kotlinlang.org/docs/reference/functions.html#unit-returning-functions

