Implicit conversion from A to Some(a)

后端 未结 3 1957
眼角桃花
眼角桃花 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:01

    Possible, yes:

    object Test {
      implicit def anythingToOption[A](a: A): Option[A] = Option(a)
      def foo(something: Option[Int]): Unit = ???
    
      def main(args: Array[String]): Unit = {
        foo(1)
      }
    }
    

    Should you do this? NO. Why? Because implicits with such broad scopes are dangerous. For one, they can lead to ambiguity when you actually need a relevant implicit in scope. Second, when someone reads this, they'll need to see where this conversion happens, and why. Third, this can lead to subtle bugs.

    Instead, you can use extension methods, whether you get them from the Cats library or write them yourself:

    object Test {
      implicit class OptionOps[A](val a: A) extends AnyVal {
        def toOption: Option[A] = Option(a)
        def some: Option[A] = Some(a)
      }
    
      def foo(something: Option[Int]): Unit = ???
      def main(args: Array[String]): Unit = {
        foo(1.toOption)
        foo(1.some)
      }
    }
    

提交回复
热议问题