classApplyOperation{ } classApplyTest{ defapply(b:String) = println(b+":I am into spark so much!!!") defhaveATry: Unit ={ println("have a try on apply") } } objectApplyTest{ defapply(i:Int) = { println(i.toString+":I am into Scala so much") newApplyTest } } objectApplyOperation{ defmain(args: Array[String]) { val array= Array(1,2,3,4) val a = ApplyTest(111) //这里就是使用object 的使用 val b= ApplyTest.apply(222)
val p0 = newPerson("Frank", 23, "Blue") // normal constructor val p1 = Person("Frank", 23, "Blue") // this uses apply val p2 = Person.apply("Frank", 23, "Blue") // using apply manually
abstractclassDatabaseDriver{ // some database stuff } objectDatabaseDriver{ defapply(config: Configuration) = config.dbType match { case"MYSQL" => newMySqlDriver() case"PSQL" => newPostgresDriver() case _ => newGenericDriver() } } // now I get the right version! val mydatabase = DatabaseDriver(dbConfig)
4、apply应用于匿名函数
两个语句一样的结果:
5、在class中的apply
可以在object中有apply方法,当然也在class中定义apply方法
1 2 3 4 5 6 7 8 9 10 11
classAmazing{ defapply(x: String) = "Amazing %s!".format(x) } // look how cool this is val amazing = newAmazing() amazing("world") // => Amazing world! amazing.apply("world") // => Amazing world!