Adding object methods implicitly

后端 未结 2 1437
忘掉有多难
忘掉有多难 2021-01-02 11:51

Is there a way to implicitly add methods in scala object?

Upd: For example, Unfiltered scala library have singleton object Body which contains methods

相关标签:
2条回答
  • 2021-01-02 12:13

    What do you mean by implicitly adding methods? Does this code snipper answer your question:

    implicit def toFunkyString(s: String) = new {
      def reverseUpper = s.reverse.toUpperCase
    }
    
    "Foo".reverseUpper  //yields 'OOF'
    toFunkyString("Foo").reverseUpper  //explicit invocation
    
    0 讨论(0)
  • 2021-01-02 12:40
    import scala.language.implicitConversions
    
    object ObjA
    
    object ObjB {
      def x = 1
    }
    
    object Main {
        implicit def fromObjA(objA: ObjA.type) = ObjB
    
        def main(args: Array[String]): Unit = {
            println(ObjA.x)
        }
    }
    
    0 讨论(0)
提交回复
热议问题