Binary strings: Difference between revisions

→‎{{header|Kotlin}}: Updated example see https://github.com/dkandalov/rosettacode-kotlin for details
(Added Kotlin)
(→‎{{header|Kotlin}}: Updated example see https://github.com/dkandalov/rosettacode-kotlin for details)
Line 1,500:
 
The implementation is not intended to be particularly efficient as I've sometimes delegated to the corresponding String class functions in the interests of both simplicity and brevity. Moreover, when Java 9's 'compact strings' feature is implemented, it won't even save memory as Strings which don't contain characters with code-points above 255 are apparently going to be flagged and stored internally as arrays of single bytes by the JVM, not arrays of 2 byte characters as at present.
<lang scala>class ByteString(private val bytes: ByteArray) : Comparable<ByteString> {
<lang scala>// version 1.1.2
class ByteString(private val bytes: ByteArray) : Comparable<ByteString> {
val length get() = bytes.size
 
fun isEmpty() = bytes.size == 0isEmpty()
 
operator fun plus(other: ByteString): ByteString = ByteString(bytes + other.bytes)
Line 1,514 ⟶ 1,512:
require (index in 0 until length)
return bytes[index]
}
 
fun toByteArray() = bytes
Line 1,531 ⟶ 1,529:
fun substring(startIndex: Int) = ByteString(bytes.sliceArray(startIndex until length))
 
fun substring(startIndex: Int, endIndex: Int) =
ByteString(bytes.sliceArray(startIndex until endIndex))
 
Line 1,537 ⟶ 1,535:
val ba = ByteArray(length) { if (bytes[it] == oldByte) newByte else bytes[it] }
return ByteString(ba)
}
 
fun replace(oldValue: ByteString, newValue: ByteString) =
this.toString().replace(oldValue.toString(), newValue.toString()).toByteString()
 
override fun toString(): String {
Line 1,551 ⟶ 1,549:
}
return chars.joinToString("")
}
}
 
Line 1,566 ⟶ 1,564:
}
 
/* property to be used as an abbreviation for String.toByteString() */
val String.bs get() = this.toByteString()
 
fun main(args: Array<String>) {