Parameters And Arguments
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 56 of 93.
Functions become much more powerful when they can accept input. Parameters are variables defined in the function declaration that act as placeholders for values the function will receive.
fun greet(name: String) {
println("Hello, $name!")
}
fun main() {
greet("Alice")
greet("Bob")
}
// Output:
// Hello, Alice!
// Hello, Bob!Here, name is a parameter - it's defined inside the parentheses with its type. When we call the function, we pass an argument - the actual value like "Alice" or "Bob". The parameter receives this value and uses it inside the function.
Functions can have multiple parameters, separated by commas:
fun introduce(name: String, age: Int) {
println("$name is $age years old")
}
fun main() {
introduce("Emma", 25)
}
// Output: Emma is 25 years oldWhen calling a function with multiple parameters, the arguments must be provided in the same order as the parameters are defined. Each parameter needs its type specified, even if they're the same type.
Challenge
MediumCreate a function called describePet that takes two parameters: name (String) and age (Int).
The function should print the following message:
[name] is [age] years old.In your main function, read two inputs: a pet name (String) and an age (Int). Then call describePet with these values.
For example, if the inputs are:
Buddy
3The output should be:
Buddy is 3 years old.Try it yourself
fun main() {
// Read input
val name = readLine()!!
val age = readLine()!!.toInt()
// TODO: Create the describePet function and call it with name and age
}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