class ApplyTest{
def apply() = "APPLY"
def test: Unit ={
println("test")
}
}
object ApplyTest{
var count = 0
def apply() = new ApplyTest
def static: Unit ={
println("static")
}
def incr ={
count += 1
}
}
object Basic4 extends App{
ApplyTest.static
var a = ApplyTest()
a.test
var t = new ApplyTest
println(t())
for (i <- 1 to 10){
ApplyTest.incr
}
println(ApplyTest.count)
}
class Basic5 {
}
//case class:
// 1.构造函数中每个变量都是val不建议用var
// 2. 不用new就可以产生对象(apply方法)
case class Book(name : String, author : String, price : Int)
object Basic5 extends App{
val value = 3
//match语句实际上类似于其他语言中的switch语句,而且没有break语句,因为他匹配完成后会立即退出
var result = value match {
case 1 => "one"
case 2 => "two"
case _ => "some other values" //_代表通配符,类似其他语言的default语句
}
var result2 = value match {
case i if i == 1 => "one"
case i if i == 2 => "two"
case _ => "three"
}
println("result of match is " + result)
println("result of match is " + result2)
def t(t : Any) = t match {
case t:Int => println("Int")
case t:String => println("String")
case _ => println("unknown type")
}
t("orange")
var macTalk = Book("MacTalk", "WangCheng", 22)
macTalk match {
case Book(name, author, price) => println("This is a Book")
case _ => println("Unknown Type")
}
//常用的高阶函数map,filter,reduce
val l = List(1,2,3,4,5,6,7,8)
val mapList = l.map((x) => 2 * x)
val mapList2 = l.map(2 * _)//占位符方式,不用x
//元组
val hostPort = ("localhost", "8080")
println(hostPort _1)//注意下标从1开始
println(hostPort _2)
//map
val m = Map("a" -> "b")
m("a")
//getOrElse语句实际上类似于,if(xx != null)这种
println(m.get("a").getOrElse())
println(m.get("b").getOrElse("None"))
//foreach
//无返回值,只会产生一些副作用
mapList.foreach((x : Int) => println(3 * x))
//filter
val mapListFiltered1 = l.filter(_ % 2 == 0)
val mapListFiltered2 = l.filter(_ % 2 == 1)
println(mapListFiltered1)
println(mapListFiltered2)
//zip,配对
val zipList = mapListFiltered1.zip(mapListFiltered2)
//zip以zip调用者为准
println(zipList)
//pritition
val pList = l.partition(_%2 == 0)
println(pList)
//flatten
val lists = List(List("a", "b", "c"), List("1","2","3"),List(1))
val fList = lists.flatten
println(fList)
//flatMap
val fmList = lists.flatMap(x => x.map(_ + "2"))
println(fmList)
//泛型
//隐式转换
//1.位于原目标类型伴生对象中的隐式函数
//2.位于当前作用于可以以单个标识符指代的隐式函数
class Basic5{
}
class A{
}
class RichA(a : A){
def rich{
println("rich !")
}
}
object Basic6 extends App{
implicit def a2RichA(a : A) = new RichA(a)
val a = new A
a.rich
}
def testParam(implicit name : String): Unit ={
println(name)
}
implicit val name = "implicit!!!"
testParam
implicit class Calculator(x:Int){
def add(a:Int) = a + 1
}
println(1.add(1))
//注意,需要用到哪个隐式转换,一定需要将其引过来
}