鲁春利的工作笔记,好记性不如烂笔头
apply
需要构造有参数需求的伴生对象时,可定义并使用apply方法。
class HelloWorld (var m : String, var n : Char) { println("I‘m class HelloWorld!"); def speak () { println("Class HelloWorld Speak."); } } object HelloWorld { def apply(n : Char) = new HelloWorld("The char is ", n); def speak () { println("Object HelloWorld Speak."); } } val hi = HelloWorld.apply(‘s‘); HelloWorld.speak(); hi.speak();
运行scala文件
G:\Hadoop\scala-SDK\source>scala companions.scala I‘m class HelloWorld! Object HelloWorld Speak. Class HelloWorld Speak.
实际上,这是一种“约定”,只要你的object中定义了一个apply方法,你是可以直接使用object的名字作为函数名实现对这个apply方法的调用!
单例对象、伴生对象、apply方法使用
/** * @author lucl */ final class Person private { var name : String = ""; // 可以直接访问伴随对象的成员 println("The first NO of class Person is " + Person.NO); def apply () = { println("This is apply method in class Person."); } def foo () { println("The foo method of class Person."); } def this (name : String) { this; this.name = name; } } /** * 类的伴生对象 * object修饰的为单例对象,其所有成员均是静态的 */ object Person { private var NO : Int = 0; def nextNo { NO += 1; } def apply() = { println("This is apply method in object Person.") new Person(); } def apply (name : String) = { println("This is apply method in object Person with name " + name + "."); new Person (name); } def foo () { println("The foo method of object Person."); } } object OOPTest { def main (args : Array[String]) { // println("----------------------------------"); // 当class Person的主构造函数通过private修饰后则new Person()不可再被访问 // val a = new Person(); // The first NO of class Person is 0 // a.foo(); // The foo method of class Person. // println(a); // println(a()); // 会调用类的apply方法,输出This is apply method in class Person. println("----------------------------------"); val b = Person; b.foo; // The foo method of object Person. println("----------------------------------"); val c = Person.apply; // This is apply method in object Person. c.foo(); // The foo method of class Person. println(c()); // This is apply method in class Person. println("----------------------------------"); val d = Person("zhangsan"); // 实际调用object Person的apply(name : String)方法 println("The name set by object Person apply method is : " + d.name); // var e = Array(1, 2, 3, 4, 5); } } /** ---------------------------------- The foo method of object Person. ---------------------------------- This is apply method in object Person. The first NO of class Person is 0 The foo method of class Person. This is apply method in class Person. () ---------------------------------- This is apply method in object Person with name zhangsan. The first NO of class Person is 0 The name set by object Person apply method is : zhangsan */
实际上查看Array数组时也可以发现,通过IDE工具把鼠标放到Array上能看到调用的为apply方法:
按下Ctrl键,然后通过数据点进去查看代码时看到的是:
object Array extends FallbackArrayBuilding 的apply方法:
而实际Array类的定义为:
final class Array[T](_length: Int) extends java.io.Serializable with java.lang.Cloneable {......}
时间: 2024-10-11 04:20:34