代码之家  ›  专栏  ›  技术社区  ›  Álvaro Valencia

泛型函数中的隐式转换

  •  0
  • Álvaro Valencia  · 技术社区  · 8 年前

      def convertAny[T](any: Any)(implicit run: Any => Option[T]) = run.apply(any)
      implicit def anyToDouble(any: Any) = Try(any.asInstanceOf[Double]).toOption
      implicit def anyToInt(any: Any) = Try(any.asInstanceOf[Int]).toOption
    

    问题是我需要在像这样的通用函数中进行这些转换:

      def doStuffAndConvert[T](i: Any): Option[T] = {
        // Some pre-processing
        println("Processing data...")
    
        convertAny[T](i)
      }
    

    doStuffAndConvert 以下内容:

    doStuffAndConvert[Double](a)
    

    Error:(40, 18) No implicit view available from Any => Option[T].
        convertAny[T](i)
    

    我试图通过包装int和double类型并绑定 T

    我怎么修?

    1 回复  |  直到 8 年前
        1
  •  2
  •   Alexey Romanov    8 年前

    convertAny doStuffAndConvert

    def doStuffAndConvert[T](i: Any)(implicit run: Any => Option[T]): Option[T] = {
      // Some pre-processing
      println("Processing data...")
    
      convertAny[T](i) // or just i, the implicit will be used anyway
    }
    

    含蓄的像 anyToDouble/Int

    推荐文章