-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)={
}
}