gpt4 book ai didi

Scala 任何数字类型的隐式转换

转载 作者:行者123 更新时间:2023-12-04 16:06:12 26 4
gpt4 key购买 nike

我目前正在学习 Scala 编程语言(顺便说一句,我很喜欢它)并且最近发现了隐式转换。所以我有我的类 Complex 及其伴随对象。在我的伴侣对象中,我想要这些隐式转换:

    implicit def convertToComplex(x: Double) = new Complex(x, 0);
implicit def convertToComplex(x: Int) = new Complex(x, 0);
implicit def convertToComplex(x: Float) = new Complex(x, 0);
implicit def convertToComplex(x: Short) = new Complex(x, 0);
implicit def convertToComplex(x: Long) = new Complex(x, 0);

为了不让我的 Complex number 类因加号类型的 +、-、* 和/重载而膨胀。

所以我的问题是:

有没有更短的方法来使用某种语法糖来编写隐式转换? (我的意思是没有所有的重载...)

提前致谢。

最佳答案

你可以这样做

object ConvertComplex {
case class Complex[T: Numeric](x: T, y: Int) {

val nX = implicitly[Numeric[T]]

def doSomething = nX.toInt(x) * y
def doSomethingElse = nX.plus(x, nX.fromInt(y))
}

object Complex {
implicit def convertToComplect[T: Numeric](x: T) = Complex(x, 0)
}

}

以及测试结果:

def doSomething[T: Numeric](x: Complex[T]) = x.doSomething
def doSomethingElse[T: Numeric](x: Complex[T]) = x.doSomething

val double = 1: Double //> double : Double = 1.0
val int = 1: Int //> int : Int = 1
val float = 1: Float //> float : Float = 1.0
val short = 1: Short //> short : Short = 1
val long = 1: Long //> long : Long = 1

doSomething(double) //> res0: Int = 0
doSomething(int) //> res1: Int = 0
doSomething(float) //> res2: Int = 0
doSomething(short) //> res3: Int = 0
doSomething(long) //> res4: Int = 0

doSomethingElse(double) //> res5: Double = 1.0
doSomethingElse(int) //> res6: Int = 1
doSomethingElse(float) //> res7: Float = 1.0
doSomethingElse(short) //> res8: Short = 1
doSomethingElse(long) //> res9: Long = 1

关于Scala 任何数字类型的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15281472/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com