Kotlin中的类和对象之间的区别 [英] Difference between a class and object in Kotlin

查看:304
本文介绍了Kotlin中的类和对象之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Kotlin的新手,最近将一个简单的文件从java转换为Kotlin。我想知道为什么Android转换器将我的java类改为Kotlin对象。

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

转换后的Kotlin:

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

为什么不是:

class MyClass {
    ... etc ...
}

任何帮助都会非常感谢谢谢。

Any help would be greatly appreciated thanks.

推荐答案

Kotlin对象就像一个无法实例化的类,因此必须按名称调用。 (静态类本身)

A Kotlin object is like a class that can't be instantiated so it must be called by name. (a static class per se)

android转换器看到你的类只包含一个静态方法,所以它将它转换为Kotlin对象。

The android converter saw that your class contained only a static method, so it converted it to a Kotlin object.

在此处阅读更多相关信息: http://petersommerhoff.com/dev/kotlin/kotlin-for-java-devs/#objects

Read more about it here: http://petersommerhoff.com/dev/kotlin/kotlin-for-java-devs/#objects

这篇关于Kotlin中的类和对象之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆