-1.class類
和Java中類是一樣的
-2.Object對象
類比 和Java單例對象
main方法運作在此處
-3.trait
類比 Java中接口Interface
隐式轉換implicit
implicit
隐式的,隐藏的
偷偷摸摸
關鍵詞:
修飾class,修飾def,修飾變量,修飾參數
案例1:
/**
*建立一個類
* -1.屬性field,attribute:名詞
* -2.方法method/函數function:動詞
*/
class People {
/**
* 屬性定義
*/
//當屬性使用var聲明的時候,編譯的時候,會生成Getter和setter方法
var name:String = _
//當屬性使用val聲明的時候,編譯的時候,會生成Getter方法
val age:Int = 17
/**
* 方法定義
*/
def watchFootBall(teamName:String):Unit= {
println(s"$name is watching match of $teamName")
}
def sayHello(name:String):String = {
s"Hello $name"
}
}
object SimpleObjectDemo {
def main(args: Array[String]): Unit = {
//建立一個對象
val people = new People()
//設定名稱
people.name = "huadian"
//擷取屬性的值
println(s"name is ${people.name}")
println(s"age is ${people.age}")
people.watchFootBall("Chelse")
println(people.sayHello("laosun"))
}
}
* 在Scala中構造函數有2種
* 構造函數的功能:在建立類的對象的時候,進行初始化操作
* -1.主構造函數
* 隻有一個
* 直接 緊跟 在 類class後面,如果沒有屬性的話,可以省略()
* -2.附屬構造函數
* 可以有很多
*
* 一個.scala檔案中,一個類的名字和對象的名字一緻,
* 互為伴生對象和伴生類
* 可以互相通路私有的屬性和方法
//伴生類
class People(val name:String,val age:Int){
var school:String = "huadian"
private val money:Double = 10000000.0
//定義附屬構造函數
def this(_name:String,_age:Int,_school:String){
//第一行必須調用主構造函數
this(_name,_age)
this.school = _school
println(People.yaoshi)
}
def this(_name:String,_school:String){
//第一行必須調用主構造函數
this(_name,18)
this.school = _school
}
}
//伴生對象
object People{
private val yaoshi:String = "XXXX"
def apply( name: String, age: Int): People = new People( name, age)
def apply( name: String, age: Int,school:String): People = new People( name, age,school)
def getMoney():Unit={
println((new People("zs",11)).money)
}
}
* 定義一個Trait,用于實作 與 人打招呼
*
* 和Java中interface一樣
trait HelloTrait {
def sayHello(name:String)
}
/**
* 定義一個Trait,用于 交朋友
*/
trait MakeFriendsTrait {
def makeFriends(people:People)
}
class People(val name:String) extends HelloTrait with MakeFriendsTrait {
override def sayHello(name: String): Unit = {
println(s"Hello $name")
}
override def makeFriends(people: People): Unit = {
println(s"my name is $name ,you name is ${people.name}")
}
}
object TraitDemo {
def main(args: Array[String]): Unit = {
val p1 = new People("xyy")
val p2 = new People("小姐姐")
p1.sayHello("小哥哥")
p1.makeFriends(p2)
}
}
異常地處理:
object ExceptionDemo {
def main(args: Array[String]): Unit = {
/**
* Java 中異常處理
* try{
* ....
* }catch(Exception){
* ....
* }finally{
* ....
* }
*/
try {
val result = 1/"xx".toInt
}catch {
case e:Exception =>processException(e)
}finally {
println("finally..........")
}
}
//根據不同異常的類型 進行不同的處理
def processException(e:Exception): Unit ={
e match {
case e:ArithmeticException=>{
println("ArithmeticException")
e.printStackTrace()
}
case e:NumberFormatException=>{
println("數字格式化錯誤")
e.printStackTrace()
}
case e:Exception => e.printStackTrace()
}
}
}

模式比對使用:
object PatternDemo {
def main(args: Array[String]): Unit = {
judgeGrade("F","zs")
val list: List[(String, (String, Int))] = List(("A",("a",1)),("B",("B",2)),("C",("c",3)))
//擷取List中int類型資料
list.map(tuple => tuple._2._2)
//使用模式比對
val xx: List[Int] = list.map{
case (ip,(name,age)) =>age
}
val list2: List[Array[Any]] = List(Array("sz", 24, 34.98), Array("ls", 23, 90.09), Array("ww", 34, 12.89))
list2.map{
case Array(name,orderId,money) => money
}
val logInfo = "zhangsan,34,male,177777"
val Array(name,age,sex,telphone) = logInfo.split(",")
println(s"$name")
}
/**
* 根據 學生的成績(類别A,B,C,D)等級,給出不同的評語
*/
def judgeGrade(grade:String):Unit ={
grade match {
case "A" =>println("excellent.......")
case "B" =>println("good......")
case "C" =>println("just so so ......")
case _ =>println("you need to work hader")
}
}
def judgeGrade(grade:String,name:String):Unit ={
grade match {
case "A" =>println("excellent.......")
case "B" =>println("good......")
case "C" =>println("just so so ......")
case _grade if "zs".equals(name) =>println(s"just so so ${_grade}")
case _ =>println("you need to work hader")
}
}
}
option 的使用:
* Option有2個子類
* -some
* 表示有值
* -none
* 表示無值
object OptionDemo {
def main(args: Array[String]): Unit = {
val map = Map("A"->1,"B"->2)
val opt: Option[Int] = map.get("A")
//val optValue = if(opt.isDefined){ opt.get}
val optValue = if(opt.isDefined) opt.get
val x: Int = map.get("A") match {
case Some(value) =>value
case None => 0
}
/**
* def getOrElse[B1 >: B](key: A, default: => B1): B1 = get(key) match {
* case Some(v) => v
* case None => default
* }
*/
val xx = map.getOrElse("A",0)
}
}
樣例類:
case class AAA(name:String,age:Int)
//相當于下面這段代碼
class AA(name:String,age:Int)
object AA{
def apply(name: String, age: Int): AA = new AA(name, age)
}
class People
case class Student(name:String,classRoom:String) extends People
case class Teacher(name:String,subject:String) extends People
object caseClassDemo {
def main(args: Array[String]): Unit = {
val aaa = AAA("zs",18)
check(Teacher("xx","java"))
}
def check(people: People): Unit ={
people match {
case Teacher(name,subject)=>println("teacher")
case Student(name,classRoom)=>println("Student")
case _ =>println("==================")
}
}
}
隐式函數:
//普通人
class Man(val name: String)
//object Man{
// implicit def man2SuperMan(man:Man):SuperMan={
// new SuperMan(man.name)
// }
//}
object AAA{
implicit def man2SuperMan(man:Man):SuperMan={
new SuperMan(man.name)
}
}
//超人:奧特曼
class SuperMan(val name: String){
//發射雷射
def emitLaser():Unit= println("emit a laser.........")
}
object ImplicitDemo {
def main(args: Array[String]): Unit = {
val man = new Man("super")
/**
* 預設情況下:
* 找變身函數 目前可見的作用域裡面找,
* 原類型伴生對象中找 (推薦用法)
* 目前類下面找
* 手動導入
*/
import com.huadian.bigdata.oop.demo08.AAA._
man.emitLaser()
}
// implicit def man2SuperMan(man:Man):SuperMan={
// new SuperMan(man.name)
// }
}
案例:
class SignPen{
def write(name:String) = println(s"$name")
}
object SignPen{
implicit val signPen:SignPen = new SignPen
}
object ImplicitParamDemo {
def main(args: Array[String]): Unit = {
signForMeetUp("ZS")
}
//參加某個技術交流沙龍,到達會場需要簽字
def signForMeetUp(name:String)(implicit signPen: SignPen):Unit={
signPen.write(name)
}
def xxx(name:String)(age:Int)={
}
}