scala(4)Learn CH4 Programming in Scala from others

scala(4)Learn CH4 Programming in Scala from others

Classes and Objects
In scala, immutable var will not cost extra resource.
var acc = 0
var bcc = 0
There will be only 2 variables, acc and bcc, they all will equal to 0 value.

class ChecksumAccumulator {
//private member in class
private var sum = 0
//return void function
def add(b: Byte): Unit = {
sum += b
}
//return int function, the last statement will be the return value
def checksum(): Int = {
return ~(sum & 0xFF) + 1
}
}

There is no static function in Class. In scala, there is singleton, the only difference is that we change the keyword from class
to object.

object ASingleton{
var a =0
}
ASingleton.a = 1

Basic Types and Operations
package com.sillycat.easyscala

object TestMain extends App {
println("""Welcome to Ultamix 3000.
Type "HELP" for help.""")

println("""|Welcome to Ultamix 3000.
|Type "HELP" for help.""".stripMargin)
}

There are 3 types of operators in scala, infix, prefix, postfix.

prefix: -2, !flag, +n,
infix:
println("string".indexOf('t'))
println("string" indexOf "g")
println("string".indexOf('s', 0))
postfix:
println("string".toUpperCase())
println("string" toUpperCase )
== means the content of the object, not like comparing the objects in JAVA.
println("string" == "string") //true

Functional Objects
package com.sillycat.easyscala

class Rational(n: Int, d: Int) {
// check the parameter
require(d != 0, "d can not be 0")

private val g = gcd(n, d)

// default is public
val numer = n / g
val denom = d / g

def this(n: Int) = this(n, 1)

//Override a method
override def toString = n + "/" + d

def +(that: Rational): Rational = {
new Rational(n * that.denom + that.numer * d,
d * that.denom)
}

def <(that: Rational): Boolean = {
numer * that.denom < denom * that.numer
}

def max(that: Rational): Rational = {
if (this < that) that else this
}

// greatest common divisor
private def gcd(a: Int, b: Int): Int = {
if (b == 0) a else gcd(b, a % b)
}
}

var r1 = new Rational(1, 3)
var r3 = new Rational(3, 4)
println(r1 < r3) //true
println(r3 < r1) //false

references:
http://snowriver.org/blog/2011/03/19/programming-in-scala-ch4/
http://snowriver.org/blog/2011/03/19/programming-in-scala-ch5-basic-types-and-operations/
http://snowriver.org/blog/2011/03/19/programming-in-scala-ch6-functional-objects/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值