Scala学习笔记(七):Rational、隐式转换、偏函数、闭包、重复参数及柯里化
class Rational(n: Int, d: Int) {
require(d != 0)
private val g: Int = gcd(n, d)
val number: Int = n / g
val denom: Int = d / g
def this(n: Int) = this(n, 1)
override def toString: String =
if (denom != 1) number + "/" + denom else number.toString
def add(that: Rational): Rational = {
new Rational(number * that.denom + denom * that.number, denom * that.denom)
}
def +(x: Int): Rational = {
add(new Rational(x))
}
def +(that: Rational): Rational = add(that)
private def gcd(a: Int, b: Int): Int = {
if (b == 0) a else gcd(b, a % b)
}
}
object Rational extends App {
val rational1: Rational = new Rational(1, 2)
val rational2: Rational = new Rational(1, 2)
val add: Rational = rational1 + rational2
println(s"add=======>$add")
//隐式转换
implicit def intToRational(x: Int): Rational = new Rational(x)
println("Int*Iational===>" + 2 + intToRational(2))
//偏函数
val sum = (x: Int, y: Int, z: Int) => x + y + z
val b = sum(1, _: Int, 3)
println(b(1))
//闭包
val more = 1
val offset = (x: Int) => x + more
//重复参数
def echo(s: String*): Unit = s.foreach(println)
echo("a", "b")
//柯里化
def curriedSum(x: Int)(y: Int) = x + y
val add1 = (x: Int) => curriedSum(1) _
println(add1)
}
God, Grant me the SERENITY, to accept the things I cannot change,
COURAGE to change the things I can, and the WISDOM to know the difference.