Scala实战详解之第11讲 Scala中的apply实战详解

package com.dt.scalaInAction.demo_011

class ApplyTest {
    def apply() = {
        println("I am into Spark so much")
    }
    
    def haveATry = println("have a try on apply")
}

object ApplyTest {
    def apply() = {
        println("I am into Scala so much")
        new ApplyTest //通过apply返回伴生类的实例对象 这样可以采用 val a = ApplyTest() 方式返回一个ApplyTest类的实例
    }
}

/**
 * Scala中的apply实战详解
 */
object ApplyOperation {
    def main(args: Array[String]): Unit = {
        val a = ApplyTest()//这种方法会调用伴生对象的apply方法  row result:I am into Scala so much
        //a.haveATry
        
        /*
         * 方法
         * 这种不通过new的方式构建一个数组 采用的就是在类的伴生对象实现apply的方式
         */
        val arr = Array(1, 2, 3, 4, 5)
        
        
        
        
        /*
         * 通过new的方式构建对象  采用a1()可以调用该类的apply的方法
         */
        val a1 = new ApplyTest()
        //a1.haveATry
        a1()  //调用该类的apply的方法  row result:I am into Spark so much
        //println(a1())
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值