【Scala】基础7:隐式转换

Scala编译器在编译的时候如果发现类型不匹配,那么就会使用隐式转换来尝试将当前类型转换为预期的类型

在变量、方法或者类的前边用implicit修饰,就表示这是一个隐式转换规则。

需要注意的是,隐式转换是按照规则转换的,也就是说和名字无关。

编译器在同一个地方只会添加一次隐式操作,不会在添加一个隐式操作之后在此基础上再次添加隐式操作

那么什么时候会触发隐式转换呢? 

       1.调用某个函数,但是传入的参数类型与函数的参数类型不匹配

       2.使用某个类的时候,调用该类没有的方法

       3.使用某个类,虽然类中存在这个方法,但是传入的参数与方法参数不匹配

示例1:调用函数时类型不匹配

class specialPerson(val name:String)
class student(val name:String)
class elder(val name:String)

object testImplicit {

    implicit def transformToSpeicalPerson(other:Any) = {
        if(other.getClass == classOf[student]){
            val stu:student = other.asInstanceOf[student]
            new specialPerson(stu.name)
        }else if (other.getClass == classOf[elder]){
            val old:elder = other.asInstanceOf[elder]
            new specialPerson(old.name)
        }else{
            null
        }
    }

    def buyTickets(sp:specialPerson) = {
        println(s"${sp.name} needs to buy special tickets")
    }
 
    def main(args: Array[String]): Unit = {
        val older =new elder("Xxx")
        buyTickets(older)
    }
}

示例2:参数不通过显示传入

class flower{
    def sendTo(name:String) = {
        println(s"送给${name}")
    }
}

object implicitFlower{
    implicit val flower = new flower
}

object testImplicit {

    def sendToBF(name:String)(implicit f:flower) = {
        f.sendTo(name)
    }

    def sendToGF(name:String)(implicit f:flower) = {
        f.sendTo(name)
    }

    def main(args: Array[String]): Unit = {
        import implicitFlower.flower
        sendToBF("彭于晏!")
        sendToGF("桥本环奈!")
    }
}

猜你喜欢

转载自blog.csdn.net/hr786250678/article/details/86498098