28scala隐式转换

本文介绍了Scala编程中的隐式转换,通过示例展示了如何使用隐式转换增强类的功能,包括创建隐式类和使用隐式参数。示例中,隐式转换用于将普通类转换为具有额外方法的类,如让`Man`能飞行,以及为`File`增加`read`方法。此外,还展示了如何在函数中使用隐式参数进行类型转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

scala隐式转换

1. 目的

增强功能

2. 增强类

package com.hpznyf.implicitSource

import java.io.File
import scala.io.Source
import implicitAspect._
object implicitApp {
  def main(args: Array[String]): Unit = {

    val man = new Man("张三")
    man.fly()

    val file = new File("data/input/ck")
    println(file.read)
  }
}

class Man(val name: String) // File

class superMan(val name: String){  //RichFile
  def fly(): Unit ={
    println(s"$name can fly")
  }
}


class RichFile(val file:File){
  def read = Source.fromFile(file.getPath).mkString
}

切面

package com.hpznyf.implicitSource

import java.io.File


/**
 * 隐式转换切面
 */

object implicitAspect {
  implicit def man2superman(man:Man):superMan = new superMan(man.name)

  implicit def file2RichFile(file:File): RichFile = new RichFile(file)
}

3. 隐式类

package com.hpznyf.implicitSource

import java.io.File
import java.time.LocalDate
import scala.io.Source

object implicitClassApp {
  def main(args: Array[String]): Unit = {

    println(new File("data/input/ck").read)

    println(1.add(2))

    println(1.days("ago"))
    println(2.days("later"))
  }


  //在隐式类中为file增强read方法
  implicit class EnhenceFile(file:File){
    def read = Source.fromFile(file.getPath).mkString
  }

  //隐式类转换 Int 1.add(2)
  implicit  class Calculator(x: Int){
    def add(a:Int) = x + a
  }

  implicit class RichDate(day: Int){
    def days(when: String) ={
      if("ago" == when){
        LocalDate.now().plusDays(-day).toString
      }
      else if("age" == when){
        LocalDate.now().plusDays(day).toString
      }
      else{
        LocalDate.now().toString
      }

    }
  }

}

4. 隐式参数0

package com.hpznyf.implicitSource

object implicitParamsAPP {
  def main(args: Array[String]): Unit = {
    
    def add(a:Int)(implicit b:Int, c:Int) = a + b + c
    //将x= 10 映射给参数 b c
    implicit  val x = 10
    println(add(5))

  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值