Kotlin에서 클래스와 객체의 차이점
저는 Kotlin을 처음 사용하며 최근에 간단한 파일을 Java에서 Kotlin으로 변환했습니다. Android 변환기가 Java 클래스를 Kotlin 개체로 변경 한 이유가 궁금합니다.
자바:
public class MyClass {
static public int GenerateChecksumCrc16(byte bytes[]) {
int crc = 0xFFFF;
int temp;
int crc_byte;
for (byte aByte : bytes) {
crc_byte = aByte;
for (int bit_index = 0; bit_index < 8; bit_index++) {
temp = ((crc >> 15)) ^ ((crc_byte >> 7));
crc <<= 1;
crc &= 0xFFFF;
if (temp > 0) {
crc ^= 0x1021;
crc &= 0xFFFF;
}
crc_byte <<= 1;
crc_byte &= 0xFF;
}
}
return crc;
}
}
변환 된 Kotlin :
object MyClass {
fun GenerateChecksumCrc16(bytes: ByteArray): Int {
var crc = 0xFFFF
var temp: Int
var crc_byte: Int
for (aByte in bytes) {
crc_byte = aByte.toInt()
for (bit_index in 0..7) {
temp = crc shr 15 xor (crc_byte shr 7)
crc = crc shl 1
crc = crc and 0xFFFF
if (temp > 0) {
crc = crc xor 0x1021
crc = crc and 0xFFFF
}
crc_byte = crc_byte shl 1
crc_byte = crc_byte and 0xFF
}
}
return crc
}
}
그렇지 않은 이유 :
class MyClass {
... etc ...
}
어떤 도움이라도 대단히 감사하겠습니다.
Kotlin 객체는 인스턴스화 할 수없는 클래스와 같으므로 이름으로 호출해야합니다. (정적 클래스 그 자체)
Android 변환기는 클래스에 정적 메서드 만 포함되어 있음을 확인하여 Kotlin 개체로 변환했습니다.
여기에서 자세히 알아보세요 : http://petersommerhoff.com/dev/kotlin/kotlin-for-java-devs/#objects
이것에 대한 Kotlin의 문서 는 꽤 훌륭하므로 자유롭게 읽으십시오.
이 질문에 대해 선택한 답변에는 설명에 잘못된 문구가 포함되어있어 사람들을 쉽게 오도 할 수 있습니다. 예를 들어, 객체는 "말당 정적 클래스"가 아니라 a static instance of a class that there is only one of
싱글 톤이라고도하는입니다.
차이점을 보여주는 가장 좋은 방법은 디 컴파일 된 Kotlin 코드를 Java 형식으로 보는 것입니다.
다음은 Kotlin 객체와 클래스입니다.
object ExampleObject {
fun example() {
}
}
class ExampleClass {
fun example() {
}
}
를 사용하려면 ExampleClass
인스턴스를 생성해야합니다. ExampleClass().example()
하지만 객체를 사용하면 Kotlin이 단일 인스턴스를 생성하고 생성자를 호출하지 않고 대신 다음을 사용하여 정적 인스턴스에 액세스합니다. 이름 : ExampleObject.example()
.
다음은 Kotlin이 생성하는 동등한 자바 코드입니다.
Kotlin은 자바 바이트 코드로 컴파일되지만 위에서 컴파일 된 Kotlin 코드를 자바 코드로 리버스 컴파일하면 다음과 같은 결과를 얻을 수 있습니다.
public final class ExampleObject {
public static final ExampleObject INSTANCE = new ExampleObject();
private ExampleObject() { }
public final void example() {
}
}
public final class ExampleClass {
public final void example() {
}
}
You would use the object in Kotlin the following way:
ExampleObject.example()
Which would compile down to the equivalent Java byte code for:
ExampleObject.INSTANCE.example()
Why does Kotlin introduce object
s?
The primary use case of object
in Kotlin is because Kotlin tries to do away with static, and primitives, leaving us with a purely object oriented language. Kotlin still uses static
and primitives underneath the hood, but it discourages devs to use those concepts any more. Instead, now Kotlin replaces static with singleton object instances. Where you would previously use static field in Java, in Kotlin you will now create an object
, and put that field in the object
.
Interoperability with Java:
Because Kotlin is 100% interoperable with Java, sometimes you will want to expose certain APIs or fields in a way that is nicer for Java to read. To do this, you can use the @JvmStatic
annotation. By annotating a field or a function in an object
with @JvmStatic
, it will compile down to static fields which Java can use easier.
Companion Objects:
One last thing that's worth mentioning is companion object
s. In Java, you typically have classes that have some static content, but also some non-static / instance content. Kotlin allows you to do something similar with companion objects, which are object
s tied to a class
, meaning a class can access it's companion object's private functions and properties:
class ExampleClass {
companion object {
// Things that would be static in Java would go here in Kotlin
private const val str = "asdf"
}
fun example() {
// I can access private variables in my companion object
println(str)
}
}
An object is a singleton. You do not need to create an instance to use it.
A class needs to be instantiated to be used
In the same way that in Java you may say Math.sqrt(2) and you dont need to create a Math instance to use sqrt, in Kotlin you can create an object to hold these methods, and they are effectively static.
There is some info here:
https://kotlinlang.org/docs/reference/object-declarations.html
IntelliJ has obviously been smart enough to detect you need an object since you only have static java methods.
Also you can define functions without object declaration. Just in .kt file For example:
fun GenerateChecksumCrc16(bytes: ByteArray): Int {
...
}
And this function was related to package where is .kt file is declared. You can read more about it here https://kotlinlang.org/docs/reference/packages.html
Building on @speirce7's answer:
The following code shows the basic difference between a Class and an Object when it comes to Kotlin:
class ExampleClass(){
fun example(){
println("I am in the class.")
}
}
object ExampleObject{
fun example(){
println("I am in the object.")
}
}
fun main(args: Array<String>){
val exampleClass = ExampleClass() // A class needs to be instantiated.
exampleClass.example() // Running the instance of the object.
ExampleObject.example() // An object can be thought of as a Singleton and doesn't need any instantiation.
}
참고URL : https://stackoverflow.com/questions/44255946/difference-between-a-class-and-object-in-kotlin
'Nice programing' 카테고리의 다른 글
MYSQL 쿼리 / 1 주 전보다 오래된 날짜 (UTC의 모든 날짜 시간) (0) | 2020.10.15 |
---|---|
새 중첩 조각 API에서 onActivityResult ()가 호출되지 않음 (0) | 2020.10.15 |
파이썬의 배열에서 무작위 요소를 어떻게 선택합니까? (0) | 2020.10.15 |
datetime에서 1 년을 빼는 방법은 무엇입니까? (0) | 2020.10.15 |
Angular : 경로를 변경하지 않고 queryParams를 업데이트하는 방법 (0) | 2020.10.15 |