zl程序教程

您现在的位置是:首页 >  后端

当前栏目

scala隐式类代码示例

scala代码 示例 隐式
2023-09-14 09:02:02 时间

在 Scala2.10 后提供了隐式类,可以使用 implicit 声明类,隐式类的非常强大,同样可以扩展类的功能,在集合中隐式类会发挥重要的作用。

1)隐式类说明
(1)其所带的构造参数有且只能有一个。
(2)隐式类必须被定义在“类”或“伴生对象”或“包对象”里,即隐式类不能是顶
级的。
2)案例实操

object TestImplicitClass {
    implicit class MyRichInt(arg: Int) {
        def myMax(i: Int): Int = {
            if (arg < i) i else arg
        }
        def myMin(i: Int) = {
            if (arg < i) arg else i
        }
    }
    def main(args: Array[String]): Unit = {
        println(1.myMax(3))
        println(1.myMin(-1))
    }
}

运行结果:

在这里插入图片描述