Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 2: First Steps in Scalaย >ย Step 3. Define some functions - Pg. 27

S TEP 3 ยท Define some functions scala> val multiLine = | "This is the next line." multiLine: java.lang.String = This is the next line. If you realize you have typed something wrong, but the interpreter is still waiting for more input, you can escape by pressing enter twice: scala> val oops = | | You typed two blank lines. scala> Starting a new command. In the rest of the book, we'll leave out the vertical bars to make the code easier to read (and easier to copy and paste from the PDF eBook into the interpreter). Step 3. Define some functions Now that you've worked with Scala variables, you'll probably want to write some functions. Here's how you do that in Scala: scala> def max(x: Int, y: Int): Int = { if (x > y) x else y } max: (x: Int,y: Int)Int Function definitions start with def . The function's name, in this case max , is followed by a comma-separated list of parameters in parentheses. A type an- notation must follow every function parameter, preceded by a colon, because the Scala compiler (and interpreter, but from now on we'll just say compiler) does not infer function parameter types. In this example, the function named max takes two parameters, x and y , both of type Int . After the close paren- thesis of max 's parameter list you'll find another " : Int " type annotation. This one defines the result type of the max function itself. 6 Following the 6 In Java, the type of the value returned from a method is its return type. In Scala, that same concept is called result type. 27