val-keyword-scalaScala emphasizes scalability and this scalability claim is based on its immutable-state-by-default stance. In our first lesson “[cref first-steps-scala]“) we learnt that scala can declare a variable with either the var or the val keyword. Rebol can also protect a variable (the function name is protect) but it doesn’t do it by default and we can easily forget to apply it as the usual syntax isn’t as concise as Scala. Scala can declare an immutable variable in one single line:


val number = 1

Whereas Rebol needs two lines to do so:


number: 1
protect 'number

But’s it’s very easy to create a shorter syntax for Rebol so that we could write in one line as Scala something like this:


val 'number 1

close to Rebol’s syntax:


set 'number 1

In fact we just have to combine the above Set function with the Protect Function to get our val function:


val: func[word [word!] value][
    set word value
    protect word
]

let’s test it:


>> val number 1
** Script Error: number has no value
** Where: halt-view
** Near: val number 1
>>

Oops is there something wrong? No, we asked val first argument to be of word! type so we should pass ‘number instead of number like this:


>> val 'number 1
>> number
== 1
>>

Of course we must check that ‘number is really protected:


>> number: 2
** Script Error: Word number is protected, cannot modify
** Where: halt-view
** Near: number: 2
>>

Now let’s return the value variable so that we could write something like this:


1 + val 'number 1

Scala cannot do that but in Rebol we can so why not (all the more so Rebol’s set function also returns the value):


val: func[word [word!] value][
    set word value
    protect word
    value
]

If we test in Rebol’s Console (first unprotect ‘number)


>> unprotect 'number
>> val: func[word [word!] value][
[        set word value
[        protect word
[        value
[    ]
>> 1 + val 'number 1
== 2
>>

Update: my tweeter friend perekk suggested an even closer syntax:


val: func ['word [word!] value][
    set word value
    protect word
    value
]

so you can do without ‘ like this:


val number 1

Next: An equivalent of Scala Var Keyword.

1 people like this post.
Bookmark and Share