Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Variable

Which of the following variable names are valid?

  • 3 this_is_a_number
  • 5 A1
  • 7 function

Exercise

  1. Create a val called pi and assign it the value of 3.14159:

    val pi: Double = 3.14159
    
  2. Create a val called message and assign it a string value:

    val message: String = "Hello, world!"
    
  3. Create a val called age and assign it an integer value:

    val age: Int = 30
    
  4. Create a val called isTall and assign it a boolean value:

    val isTall: Boolean = true
    
  5. Create a val called name and assign it a string value, then print a message that includes the value of name:

val name: String = "Alice"
println(s"My name is $name.")

In this example, the string interpolation syntax is used to include the value of name in the printed message. The dollar sign ($) followed by the variable name is replaced with the value of the variable. The s at the beginning of the string indicates that this is a string interpolation.