Implicit conversion from A to Some(a)

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

    My favorite solution is this:

    class Opt[A](val value: Option[A]) extends AnyVal
    object Opt {
       implicit def fromA[A](x: A): Opt[A] = new Opt(Some(x))
       implicit def toOption[A](x: Opt[A]): Option[A] = x.value
       def N[A]: Opt[A] = new Opt(None) 
    }
    
    def myMethod(
      a: Opt[A] = Opt.N,
      ...
      z: Opt[Z] = Opt.N
    ): Something = ...
    

    Because Opt is used only for default parameters, the implicit conversions are harmless.

提交回复
热议问题