scala 隐式转换与隐式参数如何使用

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

scala 隐式转换与隐式参数如何使用

  2021-04-02 我要评论

隐式转换和隐式参数

Scala总共有三个地方会使用隐式定义:

  • 转换到一个预期的类型
  • 对某个(成员)选择接收端(字段、方法调用等)的转换
  • 隐式参数

隐式规则

  • 标记规则:只有标记为implicit的定义才可用。可标记任何变量、函数、对象
  • 作用域规则:被插入的隐式转换必须是当前作用域的单个标识符,或者跟隐式转换的源类型或目标类型有关联
  • 每次一个规则:每次只能有一个隐式定义被插入
  • 比如编译器绝不会将x+y重写为convert2(convert1(x))+y
  • 显示优先规则:只要代码按编写的样子能通过类型检查,就不尝试隐式定义

隐式转到到一个预期的类型

写过HBase的时候,都知道要写大量的Bytes.toBytes()吧,那么使用隐式转换吧。

object HBasePref {

 implicit def Str2Bytes(value: Any): Array[Byte] = value match {

  case str: String => Bytes.toBytes(str)
  case long: Long => Bytes.toBytes(long)
  case double:Double => Bytes.toBytes(double)
 }

 implicit def str2HBaseTableName(str: String): TableName = TableName.valueOf(str)
}

与新类型互相操作

你期望能够运行1 + new Rational(1,2)这个代码,但int类型显然没有这个方法。用隐式转换吧

implicit def intToRational(x:Int) = new Rational(1,1)

模拟新的语法

还记得Map初始化的->标识符吗?这么骚的操作也是隐式转换干的

隐式类

如果你经常要构造某个类,那么隐式的骚操作就可以这么干。

case class Rectangle(width,height)

implicit class RectangleMaker(width:Int) {
  def x(height:Int) = Rectangle(width,height)
}

val myRectangle = 3 x 4

隐式参数

class PreferredPromt(val preference:String)

object JoesPrefs {
  implicit val promt = new PreferredPrompt("Yes master>")}

object Greeter {
  def greet(name:String)(implicit prompt:PreferredPromt) = {
    println("Welcome," + name)
    println(prompt.preference)
  }
}

import JoesPrefs._

Greeter.greet("ljk")

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们