1.Trait
object CH_0213_Trait {
def main(args: Array[String]): Unit = {
val intelligentCar = new IntelligentCar()
intelligentCar.fly()
intelligentCar.say()
intelligentCar.drive()
}
}
trait Person {
def say(): Unit ={
println("Say something....")
}
}
trait Car {
def drive()={
println("driving....")
}
def fly()
}
class IntelligentCar extends Car with Person {
override def fly(): Unit = {
println("Fly...")
}
}
2.样例类
object CH_0214_CaseClass {
def main(args: Array[String]): Unit = {
val book1 = Book("Python", "人民日报出版", 30)
val book2 = Book("Python", "人民日报出版", 30)
println(book1.equals(book2))
println(book1==book2)
}
}
//凡是被cass class封装的对象,如果内容一致,则都相等
case class Book(bookName:String,publisher:String,price:Int){}
3.Match
object CH_0215_Match {
def main(args: Array[String]): Unit = {
val tup: (Double, Int, String, Boolean, Int) = (1.0,88,"abc",false,44)
val iter: Iterator[Any] = tup.productIterator
val res: Iterator[Unit] = iter.map(
(x) => {
x match {
case 1 => println(s"$x...is 1")
case 88 => println(s"$x ...is 88")
case false => println(s"$x...is false")
case w: Int if w > 50 => println(s"$w...is > 50")
case _ => println("wo ye bu zhi dao sha lei xing ")
}
}
)
while(res.hasNext) res.next()
}
}
4.偏函数
object CH_0216_PartialFunction {
def main(args: Array[String]): Unit = {
def xxx:PartialFunction[ Any,String] ={
case "hello" => "val is hello"
case x:Int => s"$x...is int"
case _ => "none"
}
println(xxx(44))
println(xxx("hello"))
println(xxx("hi"))
}
}
5.隐式转换之隐式方法
object CH_0217_Implicit_Function {
def main(args: Array[String]): Unit = {
val value = new java.util.ArrayList[Int]()
value.add(10)
value.add(11)
value.add(22)
implicit def func01[T](arr:java.util.ArrayList[T])={
val arrIter = arr.iterator()
new Test01[T](arrIter)
}
value.foreach(println)
}
}
class Test01[T](itr:java.util.Iterator[T]){
def foreach(f:(T) => Unit)={
while(itr.hasNext)f(itr.next())
}
}
6.隐式转换之隐式转换类
object CH_0217_Implicit_Class {
def main(args: Array[String]): Unit = {
val value = new java.util.ArrayList[Int]()
value.add(10)
value.add(11)
value.add(22)
implicit class Test01[T](itr:java.util.Iterator[T]){
def foreach(f:(T) => Unit)={
while(itr.hasNext)f(itr.next())
}
}
implicit def func01[T](arr:java.util.ArrayList[T])={
val arrIter = arr.iterator()
new Test01[T](arrIter)
}
value.foreach(println)
}
}
7.隐式转换之隐式转换参数
object CH_0217_Implicit_Par {
def main(args: Array[String]): Unit = {
implicit val name = "zhangsan"
implicit val age:Int = 20
def func01(name:String)(implicit age:Int)={
println(s"$name $age")
}
func01("lisi")
}
}
标签:value,04,val,Scala,特性,Unit,println,def,String
From: https://www.cnblogs.com/crispy-bro/p/18325262