Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

Writing Your First Function#

Sumit Rawal answered on May 23, 2023 Popularity 1/10 Helpfulness 1/10

Contents


More Related Answers

  • first program in node js
  • how to write your first python program
  • Javascript first example
  • first
  • first

  • Writing Your First Function#

    0

    In a previous lesson, you were introduced to built-in functions; also known as methods. In this chapter, we will cover user-defined functions and learn how to write our very own functions. Let’s get straight to it and look at an example of a user-defined function.

    123

    def sum(x: Double, y: Double): Double ={

    x+y

    }

    The above function takes two integers and returns their sum. Let’s look at what is exactly happening in the code above.

    Syntax

    def is the keyword used for defining a function the same way val and var are used for defining variables.

    sum is the name of the function which you get to choose yourself. Make sure the name is meaningful to the functionality of the function.

    sum is followed by () in which you define the function parameters separated by commas. Parameters specify the type of input to be given to the function.

    (x: Double, y: Double) is telling us that our function takes two parameters. The first one is named x and must be of type Double. The second one is named y and must also be of type Double.

    After defining the parameters, we define the return type of the function which in our case is Double and is done by inserting : Double after the ().

    Inserting the return type is not required as Scala can use type inference to infer the return type of the function.

    After defining the function’s return type, we insert a =. Whatever comes after = is the body of the function and defines what the function will do. The body of the function is wrapped in curly brackets {}. You can choose not to use the curly brackets if the function’s body only consists of a single expression. 

    Popularity 1/10 Helpfulness 1/10 Language whatever
    Source: Grepper
    Tags: whatever
    Link to this answer
    Share Copy Link
    Contributed on May 23 2023
    Sumit Rawal
    0 Answers  Avg Quality 2/10


    X

    Continue with Google

    By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
    X
    Grepper Account Login Required

    Oops, You will need to install Grepper and log-in to perform this action.