Defining a type for a fixed length array

I am working with some hardware that use bit sequences of some specific number of bytes. To save myself some potential hassle I would like to make a typealias or an inline class for a ByteArray with a fixed size, more specifically I want to make types like typealias DevEUI = ByteArray(8) or some other lengths.
Is there a way to do this or do I have to make my own class with a constructor that limit it like in Java ?

I’m afraid you will have to make your own class for that. Inline classes sadly don’t support a custom constructor. As far as I understand it it’s a limitation due to java interoperability right now but might be changed in the future.
Typealiases also don’t work, since they are pretty much a C macro for type definitions. They don’t provide any functionality but to reduce the amount of typing required.
However if you override the get and set operator you can basically simulate a ByteArray at use site.

data class Foo(val byteArray: ByteArray) {
	init {
		require(byteArray.size == 8)
	}
	operator fun get(i: Int) = byteArray[i]
	operator fun set(i: Int, b: Byte) { byteArray[i] = b }
	override fun equals(other: Any?): Boolean {
		if (this === other) return true
		if (javaClass != other?.javaClass) return false
		other as Foo
		if (!byteArray.contentEquals(other.byteArray)) return false
		return true
	}
	override fun hashCode(): Int {
		return byteArray.contentHashCode()
	}
}

And you probably also want to implement Iterable and maybe implement a few infix functions for binary operations.

2 Likes