怎么在scala中使用隐式转换与隐式参数

发布时间:2021-03-23 15:48:15 作者:Leah
来源:亿速云 阅读:147

这篇文章将为大家详细讲解有关怎么在scala中使用隐式转换与隐式参数,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

隐式转换和隐式参数

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

隐式规则

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

写过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")

关于怎么在scala中使用隐式转换与隐式参数就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. Scala系列之隐式转换和隐式参数
  2. 6、Scala隐式转换

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

scala

上一篇:如何在python项目中使用set集合

下一篇:怎么在Vue项目中使用matomo统计访问流量

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》