Sclang has constants?

Fredrik Olofsson pointed this absolute shocker out to me the other day. After years and years of using SuperCollider I had no idea the language has support for constants.

Here is an example from the “Writing classes” help file which is the only help file that contains information about this as far as I can tell.

MyClass {
    const <zero = 0;
} // returns 0

Why was this implemented and why in this way ?

It seems like it is only valid as a constant classvar and nothing else. You cannot use it for instance variables and you cannot use it outside of a class definition - this latter part is the most mysterious to me. Being able to prefix variables in code and function blocks with const would be super useful but that does not seem to be the goal.

Sclang never ceases to surprise…

Actually, what’s the difference between classvar <zero = 0; and const <zero = 0;?

The const cannot be reassigned within the class, while the classvar can.

This code would throw an error when compiling the class library:

MyClass {
    const <zero_const = 0;
	classvar <zero_var = 0;

	*setZeroConst {
		zero_const = 1

	*setZeroVar {
		zero_var = 1

ERROR: You may not assign to a constant.  in file 'C:\Users\frank\AppData\Local\SuperCollider\Extensions\'
  line 7 char 2:

1 Like

You might expect it to behave like a ‘public final static’(*) variable, although it doesn’t accept many type of information. For example a const <a=[1,2,3] returns an errror.

(*) java-style

[1, 2, 3] isn’t actually an array. It’s really That is, it’s an expression that produces an array, but it isn’t the array itself.

I believe expressions must occur in a function or method block.

So I would expect this to fail as well:

MyClass {
    var <a = [1, 2, 3];
    ... etc

Also, in const <a=[1,2,3], what if the user tries a.put(0, 500)?


What about const; . This fails too. Is it also an expression ?

Yes it does.

This is a limit case. I just compared to this behaviour in java and in javascript. In both languages, you can’t change what a is referring too but you change the content of the Array.

Yes. There is no way to have an instance of the class Color without making the instance… and the only way to make the instance is to evaluate some method… and the only way to call the method to create the instance is by writing an expression for it.

The only values that are not expressions are Literals. Everything else in SC must be made by an expression.

This means that const is, practically speaking, not that useful in SC – which explains how users can go for years without ever seeing it.

Literal arrays permit const <a = #[1, 2, 3];… but, contrary to Java(Script), literal arrays are immutable (put will fail – “Attempted write to immutable object”).


1 Like