Scala implicit application method conversion

I tried the following to create a style for checking options in code:

object Test {
  trait Check
  object x extends Check
  def option() = false
  def option(xx: Check) = true
  implicit class AugmentCheck(s: String) {
    def apply() = ""
    def apply(xx: Check) = s
  }
}
import Test._

val delete = option ( x )
val force  = option (   )

val res = "mystring" (   )

But I am facing the following problem:

<console>:11: error: type mismatch;
 found   : String("mystring")
 required: ?{def apply: ?}
Note that implicit conversions are not applicable because they are ambiguous:
 both method augmentString in object Predef of type (x: String)scala.collection.
immutable.StringOps
 and method AugmentCheck in object Test of type (s: String)Test.AugmentCheck
 are possible conversion functions from String("mystring") to ?{def apply: ?}
           val res = "mystring" (   )
                     ^
<console>:11: error: String("mystring") does not take parameters
           val res = "mystring" (   )

This is unsuccessful, because even if there is ambiguity in the symbol name, there should not be any ambiguity in the function signature.

If I introduce the apply method, it works fine when there is an argument, but not without it:

           val res = "mystring" apply ( x )

           res == ""

How to remove the apply keyword in this case?

+4
source share
2 answers

Instead of representing on and off states with xor  , what about using yfor yes and nno?

object Test {
  val y = true
  val n = false
  class DefaultConfigValue[U](val v: U)
  implicit class ConfigValue[U](v: U) {
    def y = v
    def n(implicit default: DefaultConfigValue[U]) = default.v
  }
  implicit val defaultConfigString = new DefaultConfigValue("")
}

import Test._
import language.postfixOps

val delete = y
val force  = n

val res1 = "my first string"   y
val res2 = "my second string"  n

, postfixOps, , y n .

, , , ( ) y n postfix. , , , - DefaultConfigValue , no - .

+3

, .

StringOps apply(n) String, N- , . DSL.

Option , .

: x . , , .

, , ?

+1

All Articles