Scala 方法的两个同名隐式定义
我有两个隐式声明,将x“重新定义”为运算符:Scala 方法的两个同名隐式定义,scala,implicit-conversion,implicit,Scala,Implicit Conversion,Implicit,我有两个隐式声明,将x“重新定义”为运算符: import scala.io.StdIn._ import util._ import scala.language.postfixOps case class Rectangle(width: Int, height: Int) case class Circle(ratio: Integer) case class Cylinder[T](ratio: T, height: T) object implicitsExample1 {
import scala.io.StdIn._
import util._
import scala.language.postfixOps
case class Rectangle(width: Int, height: Int)
case class Circle(ratio: Integer)
case class Cylinder[T](ratio: T, height: T)
object implicitsExample1 {
implicit class RectangleMaker(width: Int) {
def x(height: Int) = Rectangle(width, height)
}
implicit class CircleMaker(ratio: Int) {
def c = Circle(ratio)
}
implicit class CylinderMaker[T](ratio: T) {
def x(height: T) = Cylinder(ratio, height)
}
def main(args: Array[String]) {
val myRectangle = 3 x 4
val myCircle = 3 c
val myCylinder = 4 x 5
println("myRectangle = " + myRectangle)
println("myCircle = " + myCircle)
println("myCylinder = " + myCylinder)
}
}
这里我的输出给出:
myRectangle = Rectangle(3,4)
myCircle = Circle(3)
myCylinder = Rectangle(4,5)
我需要做什么才能拥有这样的东西:
myCylinder = Cylinder[Int](4,5)
我知道选择的隐式转换是第一个声明的转换,但是有没有办法指定
圆柱体
的使用?尝试将矩形生成器
和圆柱体生成器
组合成一个ShapeMaker
隐式类,就像这样
implicit class ShapeMaker[T](width: T) {
def x(height: T)(implicit ev: T =:= Int) = Rectangle(width, height)
def x(height: T) = Cylinder[T](width, height)
}
并为值定义提供类型归属,如下所示
val myRectangle: Rectangle = 3 x 4
val myCircle = 3 c
val myCylinder: Cylinder[Int] = 4 x 5
哪个输出
myRectangle = Rectangle(3,4)
myCircle = Circle(3)
myCylinder = Cylinder(4,5)
尝试将
RectangleMaker
和CylinderMaker
组合成一个ShapeMaker
隐式类,如下所示
implicit class ShapeMaker[T](width: T) {
def x(height: T)(implicit ev: T =:= Int) = Rectangle(width, height)
def x(height: T) = Cylinder[T](width, height)
}
并为值定义提供类型归属,如下所示
val myRectangle: Rectangle = 3 x 4
val myCircle = 3 c
val myCylinder: Cylinder[Int] = 4 x 5
哪个输出
myRectangle = Rectangle(3,4)
myCircle = Circle(3)
myCylinder = Cylinder(4,5)
选择的隐式转换不是第一个声明的转换,而是具有最特定参数类型的转换。至少您可以执行新的CylinderMaker(4)x 5,但这不是一个很好的解决方案。选择的隐式转换不是第一个声明的转换,而是具有最特定参数类型的转换。至少你可以做新的Cylinder Maker(4)x 5,但这不是一个很好的解决方案。它的意思是:隐式ev:T=:=Int“ev是一个Int类型的变量”?是的,它被称为a。它的意思是:隐式ev:T=:=Int“ev是一个Int类型的变量”?是的,它被称为a。