Creating Constants Within a Class? Topic is solved

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
MaxAstro
Posts: 557
Joined: 05 Oct 2016, 13:00

Creating Constants Within a Class?

11 Apr 2018, 15:29

So working with classes is still pretty new to me and I'm relatively inexperienced.

Is there a way to define a constant within a class, such that, for example, in any given instance of class Cube, this.NumberOfSides always equals 6?
SirRFI
Posts: 404
Joined: 25 Nov 2015, 16:52

Re: Creating Constants Within a Class?  Topic is solved

11 Apr 2018, 16:17

Unsure if we have actual constants, but static does the trick.

Code: Select all

class MyClass
{
	static my_const := 5
	
	MyMethod()
	{
		return this.my_const
	}
}

one := new MyClass()
two := new MyClass()

MsgBox % one.my_const "`n" two.my_const "`n" one.MyMethod()
Use

Code: Select all

[/c] forum tag to share your code.
Click on [b]✔[/b] ([b][i]Accept this answer[/i][/b]) on top-right part of the post if it has answered your question / solved your problem.
swagfag
Posts: 6222
Joined: 11 Jan 2017, 17:59

Re: Creating Constants Within a Class?

11 Apr 2018, 17:23

Code: Select all

class Cube {
	sides[] {
		get {
			return 6
		}
		set {
			throw Exception("Attempted modification of const")
		}
	}
}

testCube := new Cube()
MsgBox, % testcube.sides ;result 6
testCube.sides := 3 ;exception

testCube2 := new Cube()
MsgBox, % testcube2.sides ;result 6
testCube2.sides := 5 ;exception
you should probably also clarify what exactly you mean by constant, const specifier(final, immutable) or a variable mutually shared across all instances of a given class
MaxAstro
Posts: 557
Joined: 05 Oct 2016, 13:00

Re: Creating Constants Within a Class?

12 Apr 2018, 08:10

I mean an immutable number. In my specific use case, I need to store the decimal value of an RGBA value, so that instead of needing to remember 4294967295, I can just reference this.colorWhite, and the same with three other colors I use with that class.

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: Bing [Bot], Google [Bot], Kodakku and 388 guests