1. 默認參數(shù)值
1.1 方法默認參數(shù)
def main(args: Array[String]): Unit = {
//定義打印日志方法
def log(date:Date,msg:String,level:String="Info"): Unit ={
println(s"$date $level $msg")
}
log(new Date,"你好");
log(new Date(),"你好","Info");
log(new Date(),"錯誤信息","Error");
}
默認值順序在中間的調(diào)用加上命名參數(shù)才能調(diào)用,否則報錯
def log(date:Date,level:String="Info",msg:String): Unit ={
println(s"$date $level $msg")
}
log(new Date,msg="你好");
1.2 類默認參數(shù)
def main(args: Array[String]): Unit = {
val point1 = new Point(y = 1)
point1.printLocation()
}
class Point(val x: Double = 0, val y: Double = 0){
def printLocation(): Unit ={
print(s"x=$x $y")
}
}
2. 特質(zhì) (Traits)
用于在類 (Class)之間共享程序接口 (Interface)和字段 (Fields)。 它們類似于Java 8的接口。 類和對象 (Objects)可以擴展特質(zhì),但是特質(zhì)不能被實例化,因此特質(zhì)沒有參數(shù)。
2.1 子類型
trait Animal {
def say(): Unit ={
println("animal say....")
}
def walk(): Unit ={
println("animal walk....")
}
}
//cat 繼承animal
class Cat extends Animal{
def miaomiao(): Unit ={
println("car miaomiao...")
}
}
def main(args: Array[String]): Unit = {
val cat=new Cat()
cat.miaomiao()
cat.walk()
cat.say()
}
// car miaomiao...
//animal walk....
//animal say....
2.2 擴展特征,當做接口來使用
//定義迭代器 使用泛型T
trait Iterator[T] {
def hasNext: Boolean
def next(): T
}
//自定義實現(xiàn)的Int類型的迭代器
class IntIterator(to: Int) extends Iterator[Int] {
private var current = 0
override def hasNext: Boolean = current < to
override def next(): Int = {
if (hasNext) {
val t = current
current += 1
t
} else 0
}
}
def main(args: Array[String]): Unit = {
val intIterator = new IntIterator(5)
while(intIterator.hasNext){
println(intIterator.next())
}
// 0
// 1
// 2
// 3
// 4
3.元組
元組是一個可以包含不同類型元素的類,元組是不可變的。
經(jīng)常用于函數(shù)返回多個值。
元組包含2-22給個元素之間。
3.1 定義與取值
def main(args: Array[String]): Unit = {
val t1 = Tuple1(1)
//訪問元素
println(t1._1)
val t2 = new Tuple1("asdas")
println(t2._1)
//也可以直接括號
val t3=("as",12,false)
//指定類型
val t4=("as",12,true,0.88):Tuple4[String,Int,Boolean,Double]
}
3.2 元組用于模式匹配
def main(args: Array[String]): Unit = {
val courseScores = List(("Chinese", 77), ("Math", 100), ("Geo", 0 ),("English", 55 ))
//遍歷
courseScores.foreach{ tuple => {
tuple match {
case p if(p._2 == 100) => println(s" ${p._1} score is 100")
case p if(p._2 > 60 ) => println(s" ${p._1} score is greater than 60")
case p if(p._2 == 0) => println(s" ${p._1} score is o")
case _ => println(s"不及格")
}
}
}
3.3 用于for循環(huán)
def main(args: Array[String]): Unit = {
val numPairs = List((2, 5), (3, -7), (20, 56))
for ((a, b) <- numPairs) {
println(a * b)
}
///10
//-21
//1120
}
4 高階函數(shù)
使用函數(shù)來作為參數(shù)或則返回結(jié)果。
4.1 常見的高階函數(shù)map
def main(args: Array[String]): Unit = {
var seqno = Seq(1,2,3)
val values = seqno.map(x => x * x)
for ( x <- values ){
println(x )
}
// 1
// 4
// 9
}
4.2 簡化漲薪策略代碼
//定義加薪的規(guī)則
def smallPromotion(salaries: List[Double]): List[Double] =
salaries.map(salary => salary * 1.2)
//薪資的
def greatPromotion(salaries: List[Double]): List[Double] =
salaries.map(salary => salary * math.log(salary))
//薪資
def hugePromotion(salaries: List[Double]): List[Double] =
salaries.map(salary => salary * salary)
}
去掉重復代碼,定義一個方法接口,漲薪的規(guī)則傳入函數(shù)
def promotion(salaries: List[Double], promotionFunction: Double => Double): List[Double] = {
salaries.map(promotionFunction)
}
測試
val salaries = List(2500.00,3000.00,4000.00)
//實現(xiàn)漲薪
var newsalaries= promotion(salaries,(x:Double) => x* 1.2)
for(s <- newsalaries){
print(s"$s ")
//3000.0 3600.0 4800.0
}
println()
println("-----------------------------")
println()
var newsalaries2= promotion(salaries,(x:Double) => x* x)
for(s <- newsalaries2){
print(s"$s ")
//6250000.0 9000000.0 1.6E7
}
5.嵌套方法
嵌套方法經(jīng)常使用的就是遞歸調(diào)用。
求階乘
//定義階乘
def fac(x:Int):Int = {
if (x==1) {
x
}
else {
x * fac(x-1)
}
}
//24
print(fac(4))
6.多參數(shù)列表(柯里化)
方法可以定義多個參數(shù)列表,當使用較少的參數(shù)列表調(diào)用多參數(shù)列表的方法時,會產(chǎn)生一個新的函數(shù),該函數(shù)接收剩余的參數(shù)列表作為其參數(shù)。這被稱為
柯里化
。
def foldLeft[B](z: B)(op: (B, A) => B): B = {
var acc = z
var these: LinearSeq[A] = coll
while (!these.isEmpty) {
acc = op(acc, these.head)
these = these.tail
}
acc
}
測試
val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val res = numbers.foldLeft(0)((m, n) => m + n)
print(res) // 55
7.模式匹配
7.1 簡單的模式匹配
def main(args: Array[String]): Unit = {
val x: Int = Random.nextInt(5)
val str = x match {
case 0 => "zero"
case 1 => "one"
case 2 => "two"
case _ => "other"
}
println(str)
}
8.隱式轉(zhuǎn)換
方法可以具有 隱式 參數(shù)列表,由參數(shù)列表開頭的 implicit 關(guān)鍵字標記。 如果參數(shù)列表中的參數(shù)沒有像往常一樣傳遞, Scala 將查看它是否可以獲得正確類型的隱式值,如果可以,則自動傳遞。文章來源:http://www.zghlxwxcb.cn/news/detail-461445.html
8.1 官網(wǎng)的列子
//定義一個抽象類,提供兩個方法一個add 一個unit
abstract class Monoid[A] {
def add(x: A, y: A): A
def unit: A
}
//隱式實現(xiàn)字符串的拼接
implicit val stringMonoid: Monoid[String] = new Monoid[String] {
def add(x: String, y: String): String = x concat y
def unit: String = ""
}
//隱式實現(xiàn)整型的數(shù)字相加
implicit val intMonoid: Monoid[Int] = new Monoid[Int] {
def add(x: Int, y: Int): Int = x + y
def unit: Int = 0
}
//傳入一個list實現(xiàn)不同類型的累加
def sum[A](xs: List[A])(
implicit m: Monoid[A]): A =
if (xs.isEmpty) m.unit
else m.add(xs.head, sum(xs.tail))
println(sum(List(1, 2, 3))) // 6
println(sum(List("a", "b", "c"))) //abc
完結(jié),其他的可以到官網(wǎng)看看,用到在學。文章來源地址http://www.zghlxwxcb.cn/news/detail-461445.html
到了這里,關(guān)于Scala的高級用法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!