-
Notifications
You must be signed in to change notification settings - Fork 0
Functions
Important: Functions must always be defined before they are called.
The basic syntax for creating a function in Kode is like so:
func functionName(type nameOfArg1, type nameOfArg2) returnType
# Function logic here
end functionName
Here is an example of a simple function that adds two integers:
func add(int num1, int num2) int
return num1 + num2
end add
Here is another example of a function that doesn't have a return type:
func printString(string strToPrint)
print(strToPrint)
end printString
By default, the scope of a function, i.e. all the variables it can access, is everything that was defined before it's called. For example, this would not cause errors:
val a = "hello"
func add() int
return len(a)
end add
print(add())
And neither would this:
func add() int
return len(a)
end add
val a = "hello"
print(add())
However, this will cause an undefined variable error:
func add() int
return len(a)
end add
print(add())
val a = "hello"
If the user wants to have a function only have itself as scope, they can add the new
keyword in front of the call. For example, this would now cause an undefined variable error:
val a = "hello"
func add() int
return len(a)
end add
print(new add())
A function can have other functions inside of it. This doesn't affect the scope of either function. This means the child function still has access to any variables declared before it is called, even outside its parent.
However, in order to access the child, the parent must be set up in a way that it acts as a pseudo-class. In Kode, this means the parent class must be built as an object and return itself. Here is an example of parent-child functions with the parent acting as a pseudo-class:
func Parent() func
func child(int int1, int int2) int
return int1 + int2
end child
return self
end Parent
In order to access the child function, the user must first create the Parent:
val p = Parent()
print(p.child(1,2)) # prints 3
It is also possible to access it directly like so: print(Parent().child(1, 2))
.
In order to access the parent of a child, for example to refer to another child, you can use the keyword super
.
func Parent() func
func child1(int int1, int int2) int
return int1 + int2
end child1
func child2(int int3, int int4) int
return 2 * super.child1(int3, int4)
end child2
return self
end Parent
In this example, child2
would return the double of the sum.