Define a primitive data type: Difference between revisions

Added Kotlin
(Added FreeBASIC)
(Added Kotlin)
Line 863:
add( s(1); s(2)) | pp # "smallint::3"
add( s(6); s(6)) # (nothing)</lang>
 
=={{header|Kotlin}}==
There are limits to what can be done to create a 'work-alike' primitive type in Kotlin as the language doesn't support either user-defined literals or implicit conversions between types.
 
However, subject to that, the following code creates a new primitive type called TinyInt whose values lie between 1 and 10 inclusive. Instead of throwing an exception, attempting to create such a type with an out of bounds value results in a value which is within bounds i.e. 1 if the value is less than 1 or 10 if the value is greater than 10.
 
Rather than attempt to reproduce all functions or operators which the Int type supports, only the basic arithmetic operators and the increment and decrement operators are catered for below:
<lang scala>// version 1.0.6
 
class TinyInt(i: Int) {
private val value = makeTiny(i)
 
operator fun plus (other: TinyInt): TinyInt = TinyInt(this.value + other.value)
operator fun minus(other: TinyInt): TinyInt = TinyInt(this.value - other.value)
operator fun times(other: TinyInt): TinyInt = TinyInt(this.value * other.value)
operator fun div (other: TinyInt): TinyInt = TinyInt(this.value / other.value)
operator fun mod (other: TinyInt): TinyInt = TinyInt(this.value % other.value)
operator fun inc() = TinyInt(this.value + 1)
operator fun dec() = TinyInt(this.value - 1)
 
private fun makeTiny(i: Int): Int =
when {
i < 1 -> 1
i > 10 -> 10
else -> i
}
 
override fun toString(): String = value.toString()
}
 
fun main(args: Array<String>) {
var t1 = TinyInt(6)
var t2 = TinyInt(3)
println("t1 = $t1")
println("t2 = $t2")
println("t1 + t2 = ${t1 + t2}")
println("t1 - t2 = ${t1 - t2}")
println("t1 * t2 = ${t1 * t2}")
println("t1 / t2 = ${t1 / t2}")
println("t1 % t2 = ${t1 % t2}")
println("t1 + 1 = ${++t1}")
println("t2 - 1 = ${--t2}")
}</lang>
 
{{out}}
<pre>
t1 = 6
t2 = 3
t1 + t2 = 9
t1 - t2 = 3
t1 * t2 = 10
t1 / t2 = 2
t1 % t2 = 1
t1 + 1 = 7
t2 - 1 = 2
</pre>
 
=={{header|Lasso}}==
9,488

edits