Difference between a class and object in Kotlin Ask Question

Difference between a class and object in Kotlin Ask Question

I'm new to Kotlin and have recently converted a simple file from java to Kotlin. I am wondering why the Android converter changed my java class to a Kotlin object.

Java:

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;
    }
}

Converted 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
    }
}

Why wasn't it:

class MyClass {
    ... etc ...
}

Any help would be greatly appreciated thanks.

ベストアンサー1

Kotlin's documentation on this is pretty good, so feel free to read that.

The chosen answer for this question has some poor phraseology in its explanation, and could easily mislead people. For instance, an object is not "a static class per se", but rather it is a static instance of a class that there is only one of, otherwise known as a singleton.

Perhaps the best way to show the difference is to look at the decompiled Kotlin code in Java form.

Kotlin object and class:

object ExampleObject {
  fun example() {
  }
}

class ExampleClass {
  fun example() {
  }
}

In order to use the ExampleClass, you need to create an instance of it: ExampleClass().example(), but with an object, Kotlin creates a single instance of it for you, and you don't ever call it's constructor, instead you just access it's static instance by using the name: ExampleObject.example().

Equivalent Java code Kotlin would generate:

Kotlin compiles to Java byte code, but if we reverse compile the above compiled Kotlin code to Java code this is what we get:

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() {
   }
}

Kotlin ではオブジェクトを次のように使用します。

ExampleObject.example()

これは、次の同等の Java バイト コードにコンパイルされます。

ExampleObject.INSTANCE.example()

Kotlin はなぜobjects を導入するのでしょうか?

Kotlin でのの主な使用例は、objectKotlin が静的、およびプリミティブを廃止し、純粋なオブジェクト指向言語にしようとしているためです。Kotlin はstatic内部的に依然として およびプリミティブを使用していますが、開発者がこれらの概念を使用することは推奨されていません。代わりに、Kotlin では静的をシングルトン オブジェクト インスタンスに置き換えています。以前は Java で静的フィールドを使用していたところ、Kotlin では を作成しobject、そのフィールドを に配置しますobject

Javaとの相互運用性:

Kotlin は Java と 100% 相互運用可能であるため、特定の API またはフィールドを Java が読みやすい方法で公開したい場合があります。これを行うには、アノテーションを使用します@JvmStatic。フィールドまたは関数にobjectwithでアノテーションを付けると@JvmStatic、Java が簡単に使用できる静的フィールドにコンパイルされます。

コンパニオンオブジェクト:

最後に言及する価値があるのは ですcompanion object。Java では通常、静的コンテンツだけでなく非静的 / インスタンス コンテンツも含むクラスがあります。Kotlin では、objectに結び付けられた であるコンパニオン オブジェクトを使用して同様のことを行うことができますclass。つまり、クラスはコンパニオン オブジェクトのプライベート関数とプロパティにアクセスできます。

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)
  }
}

おすすめ記事