问题描述
我是 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 ...
}
非常感谢任何帮助.
推荐答案
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 中类和对象的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!