Inverse function in Scala

前端 未结 5 566
自闭症患者
自闭症患者 2021-01-02 23:01

Is there a way to express the inverse of any function in Scala?

For example if I have a function f like this:

(x: Int) => x + 1
         


        
5条回答
  •  攒了一身酷
    2021-01-02 23:09

    From pragmatistic view, unapply method could be used to represent inverse functions:

    object f {
      def apply(x: Int) = x + 1
      def unapply(x: Int) = Some(x - 1);
    }
    
    val x = 1
    val f(y) = f(x)
    
    assert(x == y)
    

提交回复
热议问题