方法的两个同名隐式定义

时间:2019-06-26 22:39:24

标签: 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 {

    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)

我知道选择的隐式转换是第一个声明的隐式转换,但是有一种方法可以指定使用Cylinder的隐式转换吗?

1 个答案:

答案 0 :(得分:4)

尝试像这样将RectangleMakerCylinderMaker组合成单个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)