AnyVal类型的所有伴生对象均提供了丰富的隐式转换方法,例如将Int值转换为Long值,可以使用int2long方法。
取自Byte的伴生对象:
implicit def byte2short(x: Byte): Short = x.toShort
implicit def byte2int(x: Byte): Int = x.toInt
implicit def byte2long(x: Byte): Long = x.toLong
implicit def byte2float(x: Byte): Float = x.toFloat
implicit def byte2double(x: Byte): Double = x.toDouble
取自Char的伴生对象:
// From the scala.Char companion object:
implicit def char2int(x: Char): Int = x.toInt
implicit def char2long(x: Char): Long = x.toLong
implicit def char2float(x: Char): Float = x.toFloat
implicit def char2double(x: Char): Double = x.toDouble
取自Short的伴生对象:
implicit def short2int(x: Short): Int = x.toInt
implicit def short2long(x: Short): Long = x.toLong
implicit def short2float(x: Short): Float = x.toFloat
implicit def short2double(x: Short): Double = x.toDouble
取自Int的伴生对象:
implicit def int2long(x: Int): Long = x.toLong
implicit def int2float(x: Int): Float = x.toFloat
implicit def int2double(x: Int): Double = x.toDouble
取自Long的伴生对象:
implicit def long2float(x: Long): Float = x.toFloat
implicit def long2double(x: Long): Double = x.toDouble
取自Float的伴生对象:
implicit def float2double(x: Float): Double = x.toDouble
BigInt和BigDecimal类定义在scala.math包中,他们可以转换来自AnyVal类型和Java中对应的实现类型。 取自BigDecimal的伴生对象:
implicit def int2bigDecimal(i: Int): BigDecimal = apply(i)
implicit def long2bigDecimal(l: Long): BigDecimal = apply(l)
implicit def double2bigDecimal(d: Double): BigDecimal = ...
implicit def javaBigDecimal2bigDecimal(x: BigDec): BigDecimal = apply(x)
其中调用apply方法时,调用了BigDecimal伴生对象的apply工厂方法。
取自BigInt的伴生对象:
implicit def int2bigInt(i: Int): BigInt = apply(i)
implicit def long2bigInt(l: Long): BigInt = apply(l)
implicit def javaBigInteger2bigInt(x: BigInteger): BigInt = apply(x)
In [ ]:
In [ ]: