笔记
学习网站:Scala教程|易百教程
作者:初生不惑
https://www.yiibai.com/scala/scala_overview.html#article-start
def functionName ([list of parameters]) : [return type]
如果不使用等号和方法体,则隐式声明抽象(abstract)方法。
def functionName ([list of parameters]) : [return type] = {
function body
return [expr]
}
例
object add {
def addInt( a:Int, b:Int ) : Int = {
var sum:Int = 0
sum = a + b
return sum
}
}
一个不返回任何东西的函数可以返回一个类似在Java中的void类型,并表示该函数不返回任何内容。 在Scala中不返回任何东西的函数称为过程。
object Hello{
def printMe( ) : Unit = {
println("Hello, Scala!")
}
}
functionName( list of parameters )
object Demo {
def main(args: Array[String]) {
println( "Returned Value : " + addInt(5,7) );
}
def addInt( a:Int, b:Int ) : Int = {
var sum:Int = 0
sum = a + b
return sum
}
}
将上述程序保存在源文件:Demo.scala中,使用以下命令编译和执行此程序。
// Shell语句
$ scalac Demo.scala
$ scala Demo
Returned Value : 12
object Demo {
def main(args: Array[String]) {
delayed(time());
}
def time() = {
println("Getting time in nano seconds")
System.nanoTime
}
def delayed( t: => Long ) = {
println("In delayed method")
println("Param: " + t)
}
}
In delayed method
Getting time in nano seconds
Param: 5331673461600740
运行结束,执行耗时:1959毫秒
object Demo {
def main(args: Array[String]) {
printInt(b = 5, a = 7);
}
def printInt( a:Int, b:Int ) = {
println("Value of a : " + a );
println("Value of b : " + b );
}
}
Value of a : 7
Value of b : 5
运行结束,执行耗时:1735毫秒
object Demo {
def main(args: Array[String]) {
printStrings("Hello", "Scala", "Python");
}
def printStrings( args:String* ) = {
var i : Int = 0;
for( arg <- args ){
println("Arg value[" + i + "] = " + arg );
i = i + 1;
}
}
}/
object Demo {
def main(args: Array[String]) {
for (i <- 1 to 10)
println( "Factorial of " + i + ": = " + factorial(i) )
}
def factorial(n: BigInt): BigInt = {
if (n <= 1)
1
else
n * factorial(n - 1)
}
}
Factorial of 1: = 1
Factorial of 2: = 2
Factorial of 3: = 6
Factorial of 4: = 24
Factorial of 5: = 120
Factorial of 6: = 720
Factorial of 7: = 5040
Factorial of 8: = 40320
Factorial of 9: = 362880
Factorial of 10: = 3628800
apply()函数接受另一个函数f和值v,并将函数f应用于v
object Demo {
def main(args: Array[String]) {
println( apply( layout, 10) )
}
def apply(f: Int => String, v: Int) = f(v)
def layout[A](x: A) = "[" + x.toString() + "]"
}
[10]
object Demo {
def main(args: Array[String]) {
println( factorial(0) )
println( factorial(1) )
println( factorial(2) )
println( factorial(3) )
}
def factorial(i: Int): Int = {
def fact(i: Int, accumulator: Int): Int = {
if (i <= 1)
accumulator
else
fact(i - 1, i * accumulator)
}
fact(i, 1)
}
}
var inc = (x:Int) => x+1
var x = inc(7)-1
//定义具有多个参数的函数
var mul = (x: Int, y: Int) => x*y
println(mul(3, 4))
// 定义不带参数的函数
var userDir = () => {
System.getProperty("user.dir") }
println( userDir )
闭包是一个函数,它返回值取决于在此函数之外声明的一个或多个变量的值。
object Demo {
def main(args: Array[String]) {
println( "multiplier(1) value = " + multiplier(1) )
println( "multiplier(2) value = " + multiplier(2) )
}
var factor = 3
val multiplier = (i:Int) => i * factor
}
在Scala中的字符串和Java中的一样,字符串是一个不可变的对象,也就是一个不能修改的对象。可以修改的对象,如数组,称为可变对象。
var greeting = "Hello world!";
// 或者
var greeting:String = "Hello world!";
object Demo {
val greeting: String = "Hello, world!"
def main(args: Array[String]) {
println( greeting )
}
}
String
类是不可变的。创建后的String
对象是无法更改的。如果有必要对字符串进行大量修改,那么可考虑使用Scala中提供的StringBuilder
类。
length()
方法
object Demo {
def main(args: Array[String]) {
var palindrome = "Dot saw I was Tod";
var len = palindrome.length();
println( "String Length is : " + len );
}
}
string1.concat(string2);
字符串通常还使用+运算符连接
object Demo {
def main(args: Array[String]) {
var str1 = "Dot saw I was ";
var str2 = "Tod";
println("Dot " + str1 + str2);
}
}
object Demo {
def main(args: Array[String]) {
var floatVar = 12.456
var intVar = 2000
var stringVar = "Hello, Scala!"
var fs = printf("The value of the float variable is " + "%f, while the value of the integer " + "variable is %d, and the string" + "is %s", floatVar, intVar, stringVar);
println(fs)
}
}
字符串插值是使用Scala编程语言创建字符串的新方法。
数组的第一个元素的索引是数字0,最后一个元素的索引是元素的总数减去1。
要在程序中使用数组,必须先声明一个变量来引用数组,并且必须指定变量可引用的数组类型。
var z:Array[String] = new Array[String](3)
// 或者
var z = new Array[String](3)
这里,变量z被声明为可以容纳三个元素的字符串数组。可以将值分配给单个元素或访问每个元素,访问元素通过使用如下命令来完成:
z(0) = "Zara"; z(1) = "Nuha"; z(4/2) = "Ayan"
还有一种定义数组的方法 -
var z = Array("Maxsu", "Nancy", "Alen")
例
object Demo {
def main(args: Array[String]) {
var myList = Array(1.9, 2.9, 3.4, 3.5)
// Print all the array elements
for ( x <- myList ) {
println( x )
}
// Summing all elements
var total = 0.0;
for ( i <- 0 to (myList.length - 1)) {
total += myList(i);
}
println("Total is " + total);
// Finding the largest element
var max = myList(0);
for ( i <- 1 to (myList.length - 1) ) {
if (myList(i) > max) max = myList(i);
}
println("Max is " + max);
}
}
Scala不直接支持各种数组操作,它提供各种方法来处理任何维度的数组。 如果要使用不同的方法,则需要导入Array._
包。
import Array._
object Demo {
def main(args: Array[String]) {
var myMatrix = ofDim[Int](3,3)
// build a matrix
for (i <- 0 to 2) {
for ( j <- 0 to 2) {
myMatrix(i)(j) = j;
}
}
// Print two dimensional array
for (i <- 0 to 2) {
for ( j <- 0 to 2) {
print(" " + myMatrix(i)(j));
}
println();
}
}
}
0 1 2
0 1 2
0 1 2
import Array._
object Demo {
def main(args: Array[String]) {
var myList1 = Array(1.9, 2.9, 3.4, 3.5)
var myList2 = Array(8.9, 7.9, 0.4, 1.5)
var myList3 = concat( myList1, myList2)
// Print all the array elements
for ( x <- myList3 ) {
println( x )
}
}
}
1.9
2.9
3.4
3.5
8.9
7.9
0.4
1.5
import Array._
object Demo {
def main(args: Array[String]) {
var myList1 = range(10, 20, 2)
var myList2 = range(10,20)
// Print all the array elements
for ( x <- myList1 ) {
print( " " + x )
}
println()
for ( x <- myList2 ) {
print( " " + x )
}
}
}
10 12 14 16 18
10 11 12 13 14 15 16 17 18 19