Scala自定义隐式转换
一、编写隐式转换类
/** * Author Mr. Guo * Create 2019/4/20 - 17:40 */ object StringImprovments { implicit class StringImprove(s: String) { def increment = s.toString.map(c => (c + 1).toChar) } implicit class Intc(i: Int) { def xx = { Integer.parseInt(i.toString) + 4 } } implicit class arrStrToArrInt(arr: Array[String]) { def toArrInt = { arr.map(arr => arr.toInt) } } implicit class arrStrToArrDouble(arr: Array[String]) { def toArrDouble: Array[Double] = { arr.map(ar => { try { ar.toDouble } catch { case x: Exception => 0.0 } }) } } }
二、隐式函数的调用
/** * Author Mr. Guo * Create 2019/4/20 - 16:44 */ object OperatorStr { def operatorStr() = { import unitlOne.StringImprovments._ val str2 = "HCL" val int1 = 3 val arrs = Array[String]("") println(str2.increment) println(int1.xx) } }
原文地址:https://www.cnblogs.com/Gxiaobai/p/10896454.html
时间: 2024-10-10 06:04:50