feat:线下课:高阶函数
This commit is contained in:
@@ -0,0 +1,77 @@
|
|||||||
|
package chapter2.demo4
|
||||||
|
|
||||||
|
object DemoMethod3 {
|
||||||
|
def main(args: Array[String]): Unit = {
|
||||||
|
|
||||||
|
// b叫做默认参数,不传值的时候,b就会等于1
|
||||||
|
def minus(a: Int, b: Int = 1): Int = {
|
||||||
|
a - b
|
||||||
|
}
|
||||||
|
|
||||||
|
def minus2(a: Int = 10, b: Int): Int = {
|
||||||
|
a - b
|
||||||
|
}
|
||||||
|
|
||||||
|
println(minus(10, 5))
|
||||||
|
// 命名参数(python),顺序可以和定义时不一致
|
||||||
|
println(minus(b = 10, a = 5))
|
||||||
|
|
||||||
|
println(minus(5))
|
||||||
|
// 报错,非命名参数调用时,参数列表和函数定义时的参数顺序默认是一致的,这里缺少了b的传递
|
||||||
|
// println(minus2(_,5))
|
||||||
|
|
||||||
|
|
||||||
|
trait Comparator[A] {
|
||||||
|
def compare(x: A, y: A): Int
|
||||||
|
}
|
||||||
|
|
||||||
|
object Comparator {
|
||||||
|
implicit object IntComparator extends Comparator[Int] {
|
||||||
|
def compare(x: Int, y: Int): Int = Integer.compare(x, y)
|
||||||
|
}
|
||||||
|
|
||||||
|
implicit object StringComparator extends Comparator[String] {
|
||||||
|
def compare(x: String, y: String): Int = x.compareTo(y)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def max[A](x: A, y: A)(implicit comparator: Comparator[A]): A =
|
||||||
|
if (comparator.compare(x, y) >= 0) x
|
||||||
|
else y
|
||||||
|
|
||||||
|
println(max(10, 6)) // 10
|
||||||
|
println(max("hello", "world")) // world
|
||||||
|
// does not compile:
|
||||||
|
// println(max(false, true))
|
||||||
|
// error: could not find implicit value for parameter comparator: Comparator[Boolean]
|
||||||
|
}
|
||||||
|
|
||||||
|
// https://docs.scala-lang.org.cn/tour/implicit-parameters.html
|
||||||
|
trait Comparator[A] {
|
||||||
|
def compare(x: A, y: A): Int
|
||||||
|
}
|
||||||
|
|
||||||
|
object Comparator {
|
||||||
|
implicit object IntComparator extends Comparator[Int] {
|
||||||
|
def compare(x: Int, y: Int): Int = Integer.compare(x, y)
|
||||||
|
}
|
||||||
|
|
||||||
|
implicit object StringComparator extends Comparator[String] {
|
||||||
|
def compare(x: String, y: String): Int = x.compareTo(y)
|
||||||
|
}
|
||||||
|
// implicit object BooleanComparator extends Comparator[Boolean] {
|
||||||
|
// def compare(x: Boolean, y: Boolean): Int = x.compareTo(y)
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
|
||||||
|
def max[A](x: A, y: A)(implicit comparator: Comparator[A]): A =
|
||||||
|
if (comparator.compare(x, y) >= 0) x
|
||||||
|
else y
|
||||||
|
|
||||||
|
println(max(10, 6)) // 10
|
||||||
|
println(max("hello", "world")) // world
|
||||||
|
// does not compile:
|
||||||
|
// println(max(false, true))
|
||||||
|
// error: could not find implicit value for parameter comparator: Comparator[Boolean]
|
||||||
|
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user