trait 类的多继承
package com.csg
//scala高级特性
object test08 {
trait Person1{
def person1Say: Unit ={
println(s"person1 ---say ")
}
def personsay()
}
trait Person2{
def person2Say: Unit ={
println(s"person2 ---say ")
}
}
class Person3 extends Person1 with Person2 {
def person3Say: Unit ={
println(s"person3 ---say ")
}
override def personsay(): Unit = {
println(s"override ---say ")
}
}
def main(args: Array[String]): Unit = {
val person3 = new Person3()
person3.person1Say
person3.person2Say
person3.person3Say
person3.personsay()
}
}
case 类型 可以判断数据是否相等一般用在判断内容,如果没有case 则输出false false有的话输出true true
package com.csg
object test09 {
case class Person1(name:String,age:Int){
}
def main(args: Array[String]): Unit = {
val person1 = new Person1("zhangsan",15)
val person2 = new Person1("zhangsan",15)
println(person1.equals(person2))
println(person1==person2)
}
}
match 方法 println 返回Unit 会有()打印
package com.csg
object t4est10 {
def main(args: Array[String]): Unit = {
val tp1 = (1.0, "123", 10, false,33)
val iterator = tp1.productIterator
val value = iterator.map(
x => x match {
case a:Double => println(s"$a is Double")
case 10 => println(s"$x is 10")
case a:Int => println(s"$a is Int")
case a:Int if a<50 => println(s"$a <50")
case _ => println(s"$x is any")
}
)
while(value.hasNext)println(value.next())
}
}
偏函数 使函数更加简洁。。输入一个int 返回一个String的偏函数
package com.csg
object test11 {
def main(args: Array[String]): Unit = {
val value : PartialFunction[Int,String]={
case 1 =>"一"
case 2 =>"二"
case 3 =>"三"
case 4 =>"四"
case _ =>"其他"
}
println(value(1))
}
}
隐式转换--隐式参数
package com.csg
object test12 {
def saySomething(age:Int)(implicit a:String): Unit ={
println(s"say--- $a age is $age")
}
def main(args: Array[String]): Unit = {
implicit val name:String ="zhangsan"
saySomething(15)
}
}
隐式函数,使函数具备其他功能 ,其实是根据传入参数的类型找到最近的隐式函数 并执行
package com.csg
object test13 {
class Animal(name:String){
def canEat(): Unit ={
println(s"$name can eat ...")
}
}
class Bird(xname:String){
val name = xname
def canFly(): Unit ={
println(s"$name can Fly ...")
}
}
def main(args: Array[String]): Unit = {
implicit def asd(bird:Bird): Animal ={
new Animal(bird.name)
}
val bird = new Bird("鸟")
bird.canFly()
bird.canEat()
}
}