Implicit conversion from A to Some(a)

后端 未结 3 1956
眼角桃花
眼角桃花 2021-01-23 00:57

out of curiosity, I was wondering if it was possible to do something like :

def myMethod(
  a: Option[A] = None,
  b: Option[B] = None, 
  ...
  z: Option[Z] = N         


        
3条回答
  •  借酒劲吻你
    2021-01-23 01:00

    as Luis Miguel Mejía Suárez suggested in the comments, you could use the cats implicit like this:

    import cats.syntax.option.catsSyntaxOptionId
    //import cats.implicits._ //or you could import everything
    
    object Example1 {
      def foo(i: Option[Int]): Boolean = ???
    
      def myFunction(a: Int, b: Int): Int =
        if (foo(a.some)) 0 else b //a.some is from cats implicit
    }
    

    What you don't want to do is expand your function to take more values just so the type matches some internal implementation.

    object Example2 {
      def foo(i: Option[Int]): Boolean = ???
    
      // don't take an option if you don't expect None
      def myFunction(a: Option[Int], b: Int): Int =
        if (foo(a)) 0 else b
    }
    

    If you're not taking None as a parameter, it's perfectly fine to convert values explicitly when you need to:

    object Example3 {
      def foo(i: Option[Int]): Boolean = ???
    
      def myFunction(a: Int, b: Int): Int =
        if (foo(Some(a))) 0 else b
    }
    

提交回复
热议问题