Search this site
Embedded Files
Squirrel of Rama
  • Home
  • Institute Coaching Programs
  • Android curriculum
    • Android Topics
      • Notification
      • Broadcast & Broadcast Receiver
      • Content Providers
      • Activities
        • Activity and Lifecycle
        • Saving state
        • Tasks and the back stack
      • Services
        • Services
        • Foreground Service
        • Bound Service
      • Dependency Injection
      • Workmanager
      • Fragment Findings*
      • Navigation findings*
      • Permissions Findings*
      • Room & Datastore findings*
    • Kotlin Topics
      • Nullables
      • Exceptions
      • Conditions and Loops
      • Arrays
      • Collections
      • Collection Functions
      • Class & Object
      • OOP Concepts
      • Scope Function
      • Visibility Modifiers
      • Generics
      • Kotlin Classes Types
        • Enums
        • Sealed Class
        • Data Classes
        • Nested and inner classes
        • Object expressions and declarations
      • Kotlin Functions Types
        • Functions
        • Extension functions
        • Higher-order functions and lambdas
      • Couroutines
      • Kotlin Flows
    • Interview Questions
      • Android Interview Questions
  • Products
    • Shabri
    • WedExhibit
  • About
Squirrel of Rama
  • Home
  • Institute Coaching Programs
  • Android curriculum
    • Android Topics
      • Notification
      • Broadcast & Broadcast Receiver
      • Content Providers
      • Activities
        • Activity and Lifecycle
        • Saving state
        • Tasks and the back stack
      • Services
        • Services
        • Foreground Service
        • Bound Service
      • Dependency Injection
      • Workmanager
      • Fragment Findings*
      • Navigation findings*
      • Permissions Findings*
      • Room & Datastore findings*
    • Kotlin Topics
      • Nullables
      • Exceptions
      • Conditions and Loops
      • Arrays
      • Collections
      • Collection Functions
      • Class & Object
      • OOP Concepts
      • Scope Function
      • Visibility Modifiers
      • Generics
      • Kotlin Classes Types
        • Enums
        • Sealed Class
        • Data Classes
        • Nested and inner classes
        • Object expressions and declarations
      • Kotlin Functions Types
        • Functions
        • Extension functions
        • Higher-order functions and lambdas
      • Couroutines
      • Kotlin Flows
    • Interview Questions
      • Android Interview Questions
  • Products
    • Shabri
    • WedExhibit
  • About
  • More
    • Home
    • Institute Coaching Programs
    • Android curriculum
      • Android Topics
        • Notification
        • Broadcast & Broadcast Receiver
        • Content Providers
        • Activities
          • Activity and Lifecycle
          • Saving state
          • Tasks and the back stack
        • Services
          • Services
          • Foreground Service
          • Bound Service
        • Dependency Injection
        • Workmanager
        • Fragment Findings*
        • Navigation findings*
        • Permissions Findings*
        • Room & Datastore findings*
      • Kotlin Topics
        • Nullables
        • Exceptions
        • Conditions and Loops
        • Arrays
        • Collections
        • Collection Functions
        • Class & Object
        • OOP Concepts
        • Scope Function
        • Visibility Modifiers
        • Generics
        • Kotlin Classes Types
          • Enums
          • Sealed Class
          • Data Classes
          • Nested and inner classes
          • Object expressions and declarations
        • Kotlin Functions Types
          • Functions
          • Extension functions
          • Higher-order functions and lambdas
        • Couroutines
        • Kotlin Flows
      • Interview Questions
        • Android Interview Questions
    • Products
      • Shabri
      • WedExhibit
    • About

Functions↗

Functions Usage
Parameters
Default arguments
Default arguments variation
Named arguments
Unit-returning functions
Single-expression functions
Variable number of arguments (varargs)
Infix notation
Function scope
Local or Nested functions
Member functions
Generic functions
Tail recursive functions↗
Video Notes

Functions Usage

Syntax

Kotlin functions are declared using the fun keyword:

fun double(x: Int): Int {

    return 2 * x

}

Parameters

Function parameters are defined using Pascal notation - name: type. Parameters are separated using commas, and each parameter must be explicitly typed:

fun powerOf(number: Int, exponent: Int): Int { /*...*/ }

Default arguments

Function parameters can have default values, which are used when you skip the corresponding argument. This reduces the number of overloads:

fun read(

    b: ByteArray,

    off: Int = 0,

    len: Int = b.size,

) { /*...*/ }


Default arguments variation

If a default parameter precedes a parameter with no default value, the default value can only be used by calling the function with named arguments:

fun foo(

    bar: Int = 0,

    baz: Int,

) { /*...*/ }


foo(baz = 1) // The default value bar = 0 is used

Named arguments

When you use named arguments in a function call, you can freely change the order that they are listed in. If you want to use their default values, you can just leave these arguments out altogether.

Consider the reformat() function, which has 4 arguments with default values.

fun reformat(

    str: String,

    normalizeCase: Boolean = true,

    upperCaseFirstLetter: Boolean = true,

    divideByCamelHumps: Boolean = false,

    wordSeparator: Char = ' ',

) { /*...*/ }


When calling this function, you don't have to name all its arguments:

reformat(

    "String!",

    false,

    upperCaseFirstLetter = false,

    divideByCamelHumps = true,

    '_'

)


You can skip all the ones with default values:

reformat("This is a long String!")


Unit-returning functions

If a function does not return a useful value, its return type is Unit. Unit is a type with only one value - Unit. This value does not have to be returned explicitly:

fun printHello(name: String?): Unit {

    if (name != null)

        println("Hello $name")

    else

        println("Hi there!")

    // `return Unit` or `return` is optional

}

Single-expression functions

When the function body consists of a single expression, the curly braces can be omitted and the body specified after an = symbol:

fun double(x: Int): Int = x * 2

Explicitly declaring the return type is optional when this can be inferred by the compiler:

fun double(x: Int) = x * 2

Variable number of arguments (varargs)

You can mark a parameter of a function (usually the last one) with the vararg modifier:

fun <T> asList(vararg ts: T): List<T> {

    val result = ArrayList<T>()

    for (t in ts) // ts is an Array

        result.add(t)

    return result

}

In this case, you can pass a variable number of arguments to the function:

val list = asList(1, 2, 3)


When you call a vararg-function, you can pass arguments individually, for example asList(1, 2, 3). If you already have an array and want to pass its contents to the function, use the spread operator (prefix the array with *):

val a = arrayOf(1, 2, 3)

val list = asList(-1, 0, *a, 4)

Infix notation

n this article, we will learn infix notation used in Kotlin functions. In Kotlin, a functions marked with infix keyword can also be called using infix notation means calling without using parenthesis and dot.
There are two types of infix function notation in Kotlin- 

  1. Standard library infix function notation

fun main(args: Array<String>) {

var a = 15

var b = 12

var c = 11

// call using dot and parenthesis

var result1 =(a > b).and(a > c)  

println("Boolean result1 = $result1")

// call using infix notation

var result2 =(a > b) and (a > c)  

println("Boolean result1 = $result2")

}

Explanation: 

Here, we have called the a.and(b) function using infix (a and b). 

Both produce the same result in the standard output.


  1. User defined infix function notation

class math {

// user defined infix member function

infix fun square(n : Int): Int{

val num = n * n

return num

}

}

fun main(args: Array<String>) {

val m = math()

// call using infix notation

val result = m square 3

print("The square of a number is: "+result)

}

The square of a number is: 9

Function scope

Kotlin functions can be declared at the top level in a file, meaning you do not need to create a class to hold a function. Kotlin functions can also be declared locally as member functions and extension functions.

Local or Nested functions

Kotlin supports local functions, which are functions inside other functions:

fun printArea(width: Int, height: Int): Unit {

   fun calculateArea(width: Int, height: Int): Int = width * height

   val area = calculateArea(width, height)

   println("The area is $area")

}

Member functions

A member function is a function that is defined inside a class or object:

class Sample {

    fun foo() { print("Foo") }

}

Generic functions

Functions can have generic parameters, which are specified using angle brackets before the function name:

fun <T> singletonList(item: T): List<T> { /*...*/ }

Tail recursive functions↗

Kotlin supports a style of functional programming known as tail recursion. For some algorithms that would normally use loops, you can use a recursive function instead without the risk of stack overflow. When a function is marked with the tailrec modifier and meets the required formal conditions, the compiler optimizes out the recursion, leaving behind a fast and efficient loop based version instead:

Disclaimer: I don't get it actually so just copy pasted the intro here.


  • Default argument can be apply on parameter of function parameter. 

  • Note: function body has parameters and the value passed to it is called arguments

Video Notes

  • Function is a block of code which is build to be reused

  • Unit is new void. which is not necessary to write in the function signature

  • We can define inline function as below. A function in a single line. remove parenthesis, add "=" operator and just write the statement at the right side of "=".

A brand by Jagrut Soni
Google Sites
Report abuse
Page details
Page updated
Google Sites
Report abuse