Declare A Function
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 55 of 93.
A function is a reusable block of code that performs a specific task. Instead of writing the same code multiple times, you define it once in a function and call it whenever needed.
In Kotlin, you declare a function using the fun keyword, followed by the function name and parentheses:
fun greet() {
println("Hello!")
}
fun main() {
greet()
greet()
}
// Output:
// Hello!
// Hello!The function greet contains one line of code, but we can call it as many times as we want. The code inside the function only runs when we call it by writing its name followed by parentheses.
Functions help organize your code into logical pieces. Each function should do one specific thing, making your program easier to read and maintain. You've actually been using a function all along: main() is the special function where your program starts executing.
Challenge
MediumDeclare a function called printWelcome that prints the following two lines when called:
Welcome to Kotlin!
Let's learn functions.In your main function, call printWelcome exactly once.
Try it yourself
// TODO: Declare your printWelcome function here
fun main() {
// TODO: Call the printWelcome function here
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground