浅谈Scala的Class、Object和Apply()方法
<p><span>Scala中如果一个Class和一个Object同名,则称Class是Object的伴生类。Scala没有Java的Static修饰符,Object下的成员和方法都是静态的,类似于Java里面加了Static修饰符的成员和方法。Class和Object都可以定义自己的Apply()方法,类名()调用Object下的Apply()方法,变量名()调用Class下的Apply()方法。</span></p><div class="jb51code">
<pre class="brush:xhtml;">
class ApplyTest{
def apply() {
println("This is a class, apply()...")
}
}
object ApplyTest{
def apply() = {
println("This is an object, apply()...")
new ApplyTest()
}
}
object ApplyExample {
def main(args: Array) {
var at=ApplyTest()
at()
}
}</pre>
</div>
<p><strong>运行结果:</strong></p>
<p style="text-align: center"><img alt="" width="230" height="43" src="https://img.jbzj.com/file_images/article/201705/201705250926416.png" /></p>
<p><span style="color: #ff0000"><strong>分析:</strong></span></p>
<div class="jb51code">
<pre class="brush:xhtml;">
var at=ApplyTest()</pre>
</div>
<p>这是类名(),调用的是Object下的Apply()方法,由于此时并没有创建类的对象,所以也只能调用Object下的静态方法。</p>
<div class="jb51code">
<pre class="brush:xhtml;">
new ApplyTest()</pre>
</div>
<p>创建了一个类的对象,并且返回给了变量at。</p>
<div class="jb51code">
<pre class="brush:xhtml;">
at()</pre>
</div>
<p>这是变量名(),显然调用的是Class的Apply()方法。</p>
<p>以上这篇浅谈Scala的Class、Object和Apply()方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持琼殿技术社区。</p>
<div class="art_xg">
<b>您可能感兴趣的文章:</b><ul><li>Scala解析Json字符串的实例详解</li><li>Scala小程序详解及实例代码</li><li>Windows7下安装Scala 2.9.2教程</li><li>PHP警告Cannot use a scalar value as an array的解决方法</li><li>php下关于Cannot use a scalar value as an array的解决办法</li><li>ExecuteReader(),ExecuteNonQuery(),ExecuteScalar(),ExecuteXmlReader()之间的区别</li><li>scala中停止循环的三种方式(推荐)</li></ul>
</div>
</div>
<!--endmain-->
頁:
[1]