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.
Advertisement
Answer
A Kotlin object is like a class that can’t be instantiated so it must be called by name. (a static class per se)
The android converter saw that your class contained only a static method, so it converted it to a Kotlin object.
Read more about it here: http://petersommerhoff.com/dev/kotlin/kotlin-for-java-devs/#objects