代码之家  ›  专栏  ›  技术社区  ›  softshipper

为什么找不到含蓄?

  •  1
  • softshipper  · 技术社区  · 6 年前

    文件中有以下定义 Show.scala :

    package com.example
    
    trait Show[A] {
      def show(a: A): String
    }
    
    object Show {
      def apply[A](implicit sh: Show[A]): Show[A] = sh
    
      //def show[A](a:A)(implicit  sh: Show[A]) = sh.show(a)
      def show[A: Show](a: A) = Show[A].show(a)
    
      implicit class ShowOps[A: Show](a: A) {
        def show = Show[A].show(a)
      }
    
      implicit val intCanShow: Show[Int] =
        new Show[Int] {
          override def show(a: Int): String = s"int $a"
        }
    
    }
    

    而在 Main.scala

    package com.example
    
    object Main extends App {
    
      println(Show.show(344))
      println(30.show)
    }  
    

    编译器抱怨:

    [error] /home/developer/scala/show/src/main/scala/com/example/Main.scala:6:14: value show is not a member of Int
    [error]   println(30.show)
    [error]              ^
    [error] one error found  
    

    2 回复  |  直到 6 年前
        1
  •  7
  •   Alejandro Alcalde    6 年前

    为了 Main Show ,你需要 import Show._ Main.scala

    package com.example
    
    object Main extends App {
      import Show._ 
      // Or import Show.ShowOps if you only want to use that implicit
    
      println(Show.show(344))
      println(30.show)
    }  
    

    Try it

    这是你的名字 implicits rules

    范围作为 单一标识符 范围内的转换。进行隐式转换 因此,您必须以某种方式将其纳入范围。 此外,除了一个例外,隐式转换必须在范围内 作为一个 . 编译器不会插入 形式someVariable.convert文件. 例如,它不会展开x+y someVariable.convert文件因此,您可以 需要导入它,这样就可以作为单个 Preamble对象,包括许多有用的隐式转换。 访问库的隐式转换

        2
  •  4
  •   Rex    6 年前

    试试这个。。

    package com.example
    
    import Show._ // add in order to access implicit..
    
    object Main extends App {
    
      println(Show.show(344))
      println(30.show)
    }  
    
    推荐文章