Scala DSL: How to add words that do nothing?

I am trying to create a simple implicit class on Intto add a function for Ints:

object Helper {
  implicit class IntHelper(i: Int) {
    def add(str: String): Int = i + str.toInt
  }
}

To be more natural to write, I would like DSL to allow this (with import Helper._):

2 add "3" and add "4"

but i cant figure out how to make a function and. I thought this would work:

object Helper {
  implicit class IntHelper(i: Int) {
    def add(str: String): Int = i + str.toInt
    def and: Int = i
  }
}

but it does not work without parentheses (indeed, it "2.add("3").and.add("4")works, but imo there are too many complete stops and parentheses for DSL).

thank

+4
source share
2 answers

, and , , , ,

(2 add "3" and) add "4"

2 add "3" and add "4"

2.add("3").and(add)."4"

DSL. , Scala, Scala, DSL, , .


, "" , and postfix infix, , . then:

object Helper {
  implicit class IntHelper(i: Int) {
    def add(str: String): Int = i + str.toInt
  }

  implicit class AndThen[A](in: A) {
    def and(t: then.type): A = in
  }

  object then
}

import Helper._

2 add "3" and then add "4"
+5

, 0__. , , 0__.

, , add, :

object Helper {
  implicit class IntHelper(i: Int) {
    def add(str: String): Int = i + str.toInt
    def and(add: AddWord): Int = i + add.str.toInt
  }

  val add = AddWord
  case class AddWord(private[Helper] val str: String)
}

:

import Helper._
1 add "3" and add("4") and add("5")
+1

All Articles