How can I create a DSL involving “blocks” where certain functions are in-scope?











up vote
0
down vote

favorite












Overview



I have a Kotlin-based project that defines a DSL, but for reasons given below I'm now investigating whether it would be better to write my project in Scala. As Scala doesn't seem to lend itself to creating DSLs with as much ease as in Kotlin, I'm not entirely sure how I'd recreate the same DSL in Scala.



Before this gets flagged as a duplicate of this question, I've looked at that but my DSL requirements are somewhat different and I haven't been able to figure out a solution from that.



Details



I'm trying to create a flow-based programming system for developing automated vehicle part test procedures, and for the past couple of weeks I've been testing out an implementation of this in Kotlin, since it seems to support a lot of features that are really nice for creating FBP systems (native coroutine support, easy creation of DSLs using type-safe builders, etc.).



As awesome as Kotlin is though, I'm starting to realise that it would help a lot if the implementation language for the FBP was more functional, since FBP's seem to share a lot in common with functional languages. In particular, being able to define and consume typeclasses would be really useful for a project like this.



In Kotlin, I've created a DSL representing the "glue" language between nodes in a flow-based system. For example, given the existence of two blackbox processes Add and Square, I can define a "composite" node that squares the sum of two numbers:



@CompositeNode
private fun CompositeOutputtingScalar<Int>.addAndSquare(x: Int, y: Int) {
val add = create<Add>()
val square = create<Square>()

connect {
input(x) to add.x
input(y) to add.y
add.output to square.input
square.output to output
}
}


The idea is that connect is a function that takes a lambda of form ConnectionContext.() -> Unit, where ConnectionContext defines various overloads of an infix function to (shadowing the built-in to function in the Kotlin stdlib) allowing me to define the connections between these processes (or nodes).



This is my attempt to do something similar in Scala:



class OutputPort[-A] {
def connectTo(inputPort: InputPort[A]) {}
}

class InputPort[+A]

object connect {
val connections = new ListBuffer[Connection[_]]()

case class Connection[A](outputPort: OutputPort[A], inputPort: InputPort[A])

class ConnectionTracker() {
def track[A](connection: Connection[A]) {}
}

// Cannot make `OutputPort.connectTo` directly return a `Connection[A]`
// without sacrificing covariance, so make an implicit wrapper class
// that does this instead
implicit class ExtendedPort[A](outputPort: OutputPort[A]) {
def |>(inputPort: InputPort[A]): Unit = {
outputPort connectTo inputPort
connections += Connection(outputPort, inputPort)
}
}
}

def someCompositeFunction() {
val output = new OutputPort[Int]
val input = new InputPort[Int]
output |> input // Should not be valid here

connect {
output |> input // Should be valid here
}
}


Right now this won't compile because ConnectablePort isn't in scope. I can bring it into scope by doing:



import connect._
connect {
output |> input // Should be valid here
}


However, it's undesirable to have to do this within the node definition.



To summarise, how can I recreate the DSL I've made in Kotlin within Scala? For reference, this is how I've defined my Kotlin DSL:



interface Composite {
fun <U : ExecutableNode> create(id: String? = null): U
fun connect(apply: ConnectionContext.() -> Unit)

class ConnectionContext {
val constants = mutableListOf<Constant<*>>()

fun <T> input(parameter: T): OutputPort<T> = error("Should not actually be invoked after annotation processing")
fun <T> input(parameterPort: OutputPort<T>) = parameterPort
fun <T> constant(value: T) = Constant(value.toString(), value)

infix fun <U, V> U.to(input: InputPort<V>): Nothing = error("Cannot connect value to specified input")
infix fun <U> OutputPort<U>.to(input: InputPort<U>) = this join input
infix fun <T, U> T.to(other: U): Nothing = error("Invalid connection")
}
}

interface CompositeOutputtingScalar<T> : Composite {
val output: InputPort<T>
}

interface CompositeOutputtingCluster<T : Cluster> : Composite {
fun <TProperty> output(output: T.() -> TProperty): InputPort<TProperty>
}









share|improve this question




















  • 1




    Scala 3 will most likely have a feature that enables "type safe builders": dotty.epfl.ch/docs/reference/implicit-function-types.html
    – Jasper-M
    Nov 12 at 15:45










  • @Jasper-M That's pretty sweet. Shame that Scala 3 won't release until 2020 at the earliest.
    – Tagc
    Nov 12 at 16:17















up vote
0
down vote

favorite












Overview



I have a Kotlin-based project that defines a DSL, but for reasons given below I'm now investigating whether it would be better to write my project in Scala. As Scala doesn't seem to lend itself to creating DSLs with as much ease as in Kotlin, I'm not entirely sure how I'd recreate the same DSL in Scala.



Before this gets flagged as a duplicate of this question, I've looked at that but my DSL requirements are somewhat different and I haven't been able to figure out a solution from that.



Details



I'm trying to create a flow-based programming system for developing automated vehicle part test procedures, and for the past couple of weeks I've been testing out an implementation of this in Kotlin, since it seems to support a lot of features that are really nice for creating FBP systems (native coroutine support, easy creation of DSLs using type-safe builders, etc.).



As awesome as Kotlin is though, I'm starting to realise that it would help a lot if the implementation language for the FBP was more functional, since FBP's seem to share a lot in common with functional languages. In particular, being able to define and consume typeclasses would be really useful for a project like this.



In Kotlin, I've created a DSL representing the "glue" language between nodes in a flow-based system. For example, given the existence of two blackbox processes Add and Square, I can define a "composite" node that squares the sum of two numbers:



@CompositeNode
private fun CompositeOutputtingScalar<Int>.addAndSquare(x: Int, y: Int) {
val add = create<Add>()
val square = create<Square>()

connect {
input(x) to add.x
input(y) to add.y
add.output to square.input
square.output to output
}
}


The idea is that connect is a function that takes a lambda of form ConnectionContext.() -> Unit, where ConnectionContext defines various overloads of an infix function to (shadowing the built-in to function in the Kotlin stdlib) allowing me to define the connections between these processes (or nodes).



This is my attempt to do something similar in Scala:



class OutputPort[-A] {
def connectTo(inputPort: InputPort[A]) {}
}

class InputPort[+A]

object connect {
val connections = new ListBuffer[Connection[_]]()

case class Connection[A](outputPort: OutputPort[A], inputPort: InputPort[A])

class ConnectionTracker() {
def track[A](connection: Connection[A]) {}
}

// Cannot make `OutputPort.connectTo` directly return a `Connection[A]`
// without sacrificing covariance, so make an implicit wrapper class
// that does this instead
implicit class ExtendedPort[A](outputPort: OutputPort[A]) {
def |>(inputPort: InputPort[A]): Unit = {
outputPort connectTo inputPort
connections += Connection(outputPort, inputPort)
}
}
}

def someCompositeFunction() {
val output = new OutputPort[Int]
val input = new InputPort[Int]
output |> input // Should not be valid here

connect {
output |> input // Should be valid here
}
}


Right now this won't compile because ConnectablePort isn't in scope. I can bring it into scope by doing:



import connect._
connect {
output |> input // Should be valid here
}


However, it's undesirable to have to do this within the node definition.



To summarise, how can I recreate the DSL I've made in Kotlin within Scala? For reference, this is how I've defined my Kotlin DSL:



interface Composite {
fun <U : ExecutableNode> create(id: String? = null): U
fun connect(apply: ConnectionContext.() -> Unit)

class ConnectionContext {
val constants = mutableListOf<Constant<*>>()

fun <T> input(parameter: T): OutputPort<T> = error("Should not actually be invoked after annotation processing")
fun <T> input(parameterPort: OutputPort<T>) = parameterPort
fun <T> constant(value: T) = Constant(value.toString(), value)

infix fun <U, V> U.to(input: InputPort<V>): Nothing = error("Cannot connect value to specified input")
infix fun <U> OutputPort<U>.to(input: InputPort<U>) = this join input
infix fun <T, U> T.to(other: U): Nothing = error("Invalid connection")
}
}

interface CompositeOutputtingScalar<T> : Composite {
val output: InputPort<T>
}

interface CompositeOutputtingCluster<T : Cluster> : Composite {
fun <TProperty> output(output: T.() -> TProperty): InputPort<TProperty>
}









share|improve this question




















  • 1




    Scala 3 will most likely have a feature that enables "type safe builders": dotty.epfl.ch/docs/reference/implicit-function-types.html
    – Jasper-M
    Nov 12 at 15:45










  • @Jasper-M That's pretty sweet. Shame that Scala 3 won't release until 2020 at the earliest.
    – Tagc
    Nov 12 at 16:17













up vote
0
down vote

favorite









up vote
0
down vote

favorite











Overview



I have a Kotlin-based project that defines a DSL, but for reasons given below I'm now investigating whether it would be better to write my project in Scala. As Scala doesn't seem to lend itself to creating DSLs with as much ease as in Kotlin, I'm not entirely sure how I'd recreate the same DSL in Scala.



Before this gets flagged as a duplicate of this question, I've looked at that but my DSL requirements are somewhat different and I haven't been able to figure out a solution from that.



Details



I'm trying to create a flow-based programming system for developing automated vehicle part test procedures, and for the past couple of weeks I've been testing out an implementation of this in Kotlin, since it seems to support a lot of features that are really nice for creating FBP systems (native coroutine support, easy creation of DSLs using type-safe builders, etc.).



As awesome as Kotlin is though, I'm starting to realise that it would help a lot if the implementation language for the FBP was more functional, since FBP's seem to share a lot in common with functional languages. In particular, being able to define and consume typeclasses would be really useful for a project like this.



In Kotlin, I've created a DSL representing the "glue" language between nodes in a flow-based system. For example, given the existence of two blackbox processes Add and Square, I can define a "composite" node that squares the sum of two numbers:



@CompositeNode
private fun CompositeOutputtingScalar<Int>.addAndSquare(x: Int, y: Int) {
val add = create<Add>()
val square = create<Square>()

connect {
input(x) to add.x
input(y) to add.y
add.output to square.input
square.output to output
}
}


The idea is that connect is a function that takes a lambda of form ConnectionContext.() -> Unit, where ConnectionContext defines various overloads of an infix function to (shadowing the built-in to function in the Kotlin stdlib) allowing me to define the connections between these processes (or nodes).



This is my attempt to do something similar in Scala:



class OutputPort[-A] {
def connectTo(inputPort: InputPort[A]) {}
}

class InputPort[+A]

object connect {
val connections = new ListBuffer[Connection[_]]()

case class Connection[A](outputPort: OutputPort[A], inputPort: InputPort[A])

class ConnectionTracker() {
def track[A](connection: Connection[A]) {}
}

// Cannot make `OutputPort.connectTo` directly return a `Connection[A]`
// without sacrificing covariance, so make an implicit wrapper class
// that does this instead
implicit class ExtendedPort[A](outputPort: OutputPort[A]) {
def |>(inputPort: InputPort[A]): Unit = {
outputPort connectTo inputPort
connections += Connection(outputPort, inputPort)
}
}
}

def someCompositeFunction() {
val output = new OutputPort[Int]
val input = new InputPort[Int]
output |> input // Should not be valid here

connect {
output |> input // Should be valid here
}
}


Right now this won't compile because ConnectablePort isn't in scope. I can bring it into scope by doing:



import connect._
connect {
output |> input // Should be valid here
}


However, it's undesirable to have to do this within the node definition.



To summarise, how can I recreate the DSL I've made in Kotlin within Scala? For reference, this is how I've defined my Kotlin DSL:



interface Composite {
fun <U : ExecutableNode> create(id: String? = null): U
fun connect(apply: ConnectionContext.() -> Unit)

class ConnectionContext {
val constants = mutableListOf<Constant<*>>()

fun <T> input(parameter: T): OutputPort<T> = error("Should not actually be invoked after annotation processing")
fun <T> input(parameterPort: OutputPort<T>) = parameterPort
fun <T> constant(value: T) = Constant(value.toString(), value)

infix fun <U, V> U.to(input: InputPort<V>): Nothing = error("Cannot connect value to specified input")
infix fun <U> OutputPort<U>.to(input: InputPort<U>) = this join input
infix fun <T, U> T.to(other: U): Nothing = error("Invalid connection")
}
}

interface CompositeOutputtingScalar<T> : Composite {
val output: InputPort<T>
}

interface CompositeOutputtingCluster<T : Cluster> : Composite {
fun <TProperty> output(output: T.() -> TProperty): InputPort<TProperty>
}









share|improve this question















Overview



I have a Kotlin-based project that defines a DSL, but for reasons given below I'm now investigating whether it would be better to write my project in Scala. As Scala doesn't seem to lend itself to creating DSLs with as much ease as in Kotlin, I'm not entirely sure how I'd recreate the same DSL in Scala.



Before this gets flagged as a duplicate of this question, I've looked at that but my DSL requirements are somewhat different and I haven't been able to figure out a solution from that.



Details



I'm trying to create a flow-based programming system for developing automated vehicle part test procedures, and for the past couple of weeks I've been testing out an implementation of this in Kotlin, since it seems to support a lot of features that are really nice for creating FBP systems (native coroutine support, easy creation of DSLs using type-safe builders, etc.).



As awesome as Kotlin is though, I'm starting to realise that it would help a lot if the implementation language for the FBP was more functional, since FBP's seem to share a lot in common with functional languages. In particular, being able to define and consume typeclasses would be really useful for a project like this.



In Kotlin, I've created a DSL representing the "glue" language between nodes in a flow-based system. For example, given the existence of two blackbox processes Add and Square, I can define a "composite" node that squares the sum of two numbers:



@CompositeNode
private fun CompositeOutputtingScalar<Int>.addAndSquare(x: Int, y: Int) {
val add = create<Add>()
val square = create<Square>()

connect {
input(x) to add.x
input(y) to add.y
add.output to square.input
square.output to output
}
}


The idea is that connect is a function that takes a lambda of form ConnectionContext.() -> Unit, where ConnectionContext defines various overloads of an infix function to (shadowing the built-in to function in the Kotlin stdlib) allowing me to define the connections between these processes (or nodes).



This is my attempt to do something similar in Scala:



class OutputPort[-A] {
def connectTo(inputPort: InputPort[A]) {}
}

class InputPort[+A]

object connect {
val connections = new ListBuffer[Connection[_]]()

case class Connection[A](outputPort: OutputPort[A], inputPort: InputPort[A])

class ConnectionTracker() {
def track[A](connection: Connection[A]) {}
}

// Cannot make `OutputPort.connectTo` directly return a `Connection[A]`
// without sacrificing covariance, so make an implicit wrapper class
// that does this instead
implicit class ExtendedPort[A](outputPort: OutputPort[A]) {
def |>(inputPort: InputPort[A]): Unit = {
outputPort connectTo inputPort
connections += Connection(outputPort, inputPort)
}
}
}

def someCompositeFunction() {
val output = new OutputPort[Int]
val input = new InputPort[Int]
output |> input // Should not be valid here

connect {
output |> input // Should be valid here
}
}


Right now this won't compile because ConnectablePort isn't in scope. I can bring it into scope by doing:



import connect._
connect {
output |> input // Should be valid here
}


However, it's undesirable to have to do this within the node definition.



To summarise, how can I recreate the DSL I've made in Kotlin within Scala? For reference, this is how I've defined my Kotlin DSL:



interface Composite {
fun <U : ExecutableNode> create(id: String? = null): U
fun connect(apply: ConnectionContext.() -> Unit)

class ConnectionContext {
val constants = mutableListOf<Constant<*>>()

fun <T> input(parameter: T): OutputPort<T> = error("Should not actually be invoked after annotation processing")
fun <T> input(parameterPort: OutputPort<T>) = parameterPort
fun <T> constant(value: T) = Constant(value.toString(), value)

infix fun <U, V> U.to(input: InputPort<V>): Nothing = error("Cannot connect value to specified input")
infix fun <U> OutputPort<U>.to(input: InputPort<U>) = this join input
infix fun <T, U> T.to(other: U): Nothing = error("Invalid connection")
}
}

interface CompositeOutputtingScalar<T> : Composite {
val output: InputPort<T>
}

interface CompositeOutputtingCluster<T : Cluster> : Composite {
fun <TProperty> output(output: T.() -> TProperty): InputPort<TProperty>
}






scala dsl






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 19:40

























asked Nov 11 at 11:09









Tagc

5,00852770




5,00852770








  • 1




    Scala 3 will most likely have a feature that enables "type safe builders": dotty.epfl.ch/docs/reference/implicit-function-types.html
    – Jasper-M
    Nov 12 at 15:45










  • @Jasper-M That's pretty sweet. Shame that Scala 3 won't release until 2020 at the earliest.
    – Tagc
    Nov 12 at 16:17














  • 1




    Scala 3 will most likely have a feature that enables "type safe builders": dotty.epfl.ch/docs/reference/implicit-function-types.html
    – Jasper-M
    Nov 12 at 15:45










  • @Jasper-M That's pretty sweet. Shame that Scala 3 won't release until 2020 at the earliest.
    – Tagc
    Nov 12 at 16:17








1




1




Scala 3 will most likely have a feature that enables "type safe builders": dotty.epfl.ch/docs/reference/implicit-function-types.html
– Jasper-M
Nov 12 at 15:45




Scala 3 will most likely have a feature that enables "type safe builders": dotty.epfl.ch/docs/reference/implicit-function-types.html
– Jasper-M
Nov 12 at 15:45












@Jasper-M That's pretty sweet. Shame that Scala 3 won't release until 2020 at the earliest.
– Tagc
Nov 12 at 16:17




@Jasper-M That's pretty sweet. Shame that Scala 3 won't release until 2020 at the earliest.
– Tagc
Nov 12 at 16:17












1 Answer
1






active

oldest

votes

















up vote
1
down vote













Just turning on the |> is pretty straightforward in Scala if you use a companion object, and is something always available with the output port



class OutputPort[-A] {
def connectTo(inputPort: InputPort[A]):Unit = {}
}

class InputPort[+A]

object OutputPort{
implicit class ConnectablePort[A](outputPort: OutputPort[A]) {
def |>(inputPort: InputPort[A]): Unit = outputPort connectTo inputPort
}
}

def someCompositeFunction() {
val output = new OutputPort[Int]
val input = new InputPort[Int]
output |> input // Should be valid here
}


Judiciously deciding where to do imports is a core Scala concept. It is how we turn on implicit in our code, like the following, is very common, since that is the way we turn on our type classes.



class OutputPort[-A] {
def connectTo(inputPort: InputPort[A]): Unit = {}
}

class InputPort[+A]

object Converter {
implicit class ConnectablePort[A](outputPort: OutputPort[A]) {
def |>(inputPort: InputPort[A]): Unit = outputPort connectTo inputPort
}
}

def someCompositeFunction() {
val output = new OutputPort[Int]
val input = new InputPort[Int]
import Converter._
output |> input // Should be valid here
}


Now, I think this is what you are looking for, but there are still some import and implicit that needs to be setup, but this would enclose the implicit behavior:



class OutputPort[-A] {
def connectTo(inputPort: InputPort[A]): Unit = {}
}

class InputPort[+A]

object Converter {

private class ConnectablePort[A](outputPort: OutputPort[A]) {
def |>(inputPort: InputPort[A]): Unit = outputPort connectTo
inputPort
}

def convert[A](f: (OutputPort[A] => ConnectablePort[A]) => Unit): Unit = {
def connectablePortWrapper(x: OutputPort[A]): ConnectablePort[A] = new ConnectablePort[A](x)

f(connectablePortWrapper _)
}
}

object MyRunner extends App {

val output = new OutputPort[Int]
val input = new InputPort[Int]

import Converter.convert

//output |> input won't work
convert[Int] { implicit wrapper =>
output |> input // Should be valid here
}
}





share|improve this answer























  • Upvoting for the effort put in and the helpful tips, but that DSL at the bottom does not look very nice compared to the Kotlin equivalent - it involves import statements, and implicit parameters that aren't used. Additionally, the block where I wire up the connections shouldn't be parameterised as the idea is that only the types for each individual connection between two ports need to match, not every connection defined within the block. I'm trying to get something as close as possible to the addAndSquare example.
    – Tagc
    Nov 11 at 19:52












  • You're right that I can make |> always available using a companion object - I've updated my post with a less-contrived example in which |> is more than just an alternative of connectTo, and therefore why it might be something I only want to be available within a particular scope. For what it's worth, the Akka DSL looks to be doing a similar kind of thing to what I'm after, but I'm still trying to understand how they do it.
    – Tagc
    Nov 11 at 19:54






  • 1




    Akka DSL and Akka Streams DSL would be a great way to find examples of what you're looking for. :)
    – Daniel Hinojosa
    Nov 11 at 19:57










  • Ah yeah, didn't know about Akka Streams. Though (from a first impression only) their DSL is slightly uglier than what's possible in Kotlin, so I suppose the bottom line is that the DSL I made in Kotlin is probably not possible to exactly reproduce in Scala, at least as an embedded DSL. It's good to have found that out now, at least.
    – Tagc
    Nov 11 at 20:07










  • @TagC From what I understand Kotlin doesn't have type classes. github.com/Kotlin/KEEP/pull/87 and that having that power is great to have in Scala. My guess is that if Kotlin would need to make TypeClasses a thing it would have to look like Scala where we have control of our import and implicit, or in Kotlin's case extension. But I am answering out of ignorance of Kotlin since I am not a professional with Kotlin. ;)
    – Daniel Hinojosa
    Nov 11 at 20:12













Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53248121%2fhow-can-i-create-a-dsl-involving-blocks-where-certain-functions-are-in-scope%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
1
down vote













Just turning on the |> is pretty straightforward in Scala if you use a companion object, and is something always available with the output port



class OutputPort[-A] {
def connectTo(inputPort: InputPort[A]):Unit = {}
}

class InputPort[+A]

object OutputPort{
implicit class ConnectablePort[A](outputPort: OutputPort[A]) {
def |>(inputPort: InputPort[A]): Unit = outputPort connectTo inputPort
}
}

def someCompositeFunction() {
val output = new OutputPort[Int]
val input = new InputPort[Int]
output |> input // Should be valid here
}


Judiciously deciding where to do imports is a core Scala concept. It is how we turn on implicit in our code, like the following, is very common, since that is the way we turn on our type classes.



class OutputPort[-A] {
def connectTo(inputPort: InputPort[A]): Unit = {}
}

class InputPort[+A]

object Converter {
implicit class ConnectablePort[A](outputPort: OutputPort[A]) {
def |>(inputPort: InputPort[A]): Unit = outputPort connectTo inputPort
}
}

def someCompositeFunction() {
val output = new OutputPort[Int]
val input = new InputPort[Int]
import Converter._
output |> input // Should be valid here
}


Now, I think this is what you are looking for, but there are still some import and implicit that needs to be setup, but this would enclose the implicit behavior:



class OutputPort[-A] {
def connectTo(inputPort: InputPort[A]): Unit = {}
}

class InputPort[+A]

object Converter {

private class ConnectablePort[A](outputPort: OutputPort[A]) {
def |>(inputPort: InputPort[A]): Unit = outputPort connectTo
inputPort
}

def convert[A](f: (OutputPort[A] => ConnectablePort[A]) => Unit): Unit = {
def connectablePortWrapper(x: OutputPort[A]): ConnectablePort[A] = new ConnectablePort[A](x)

f(connectablePortWrapper _)
}
}

object MyRunner extends App {

val output = new OutputPort[Int]
val input = new InputPort[Int]

import Converter.convert

//output |> input won't work
convert[Int] { implicit wrapper =>
output |> input // Should be valid here
}
}





share|improve this answer























  • Upvoting for the effort put in and the helpful tips, but that DSL at the bottom does not look very nice compared to the Kotlin equivalent - it involves import statements, and implicit parameters that aren't used. Additionally, the block where I wire up the connections shouldn't be parameterised as the idea is that only the types for each individual connection between two ports need to match, not every connection defined within the block. I'm trying to get something as close as possible to the addAndSquare example.
    – Tagc
    Nov 11 at 19:52












  • You're right that I can make |> always available using a companion object - I've updated my post with a less-contrived example in which |> is more than just an alternative of connectTo, and therefore why it might be something I only want to be available within a particular scope. For what it's worth, the Akka DSL looks to be doing a similar kind of thing to what I'm after, but I'm still trying to understand how they do it.
    – Tagc
    Nov 11 at 19:54






  • 1




    Akka DSL and Akka Streams DSL would be a great way to find examples of what you're looking for. :)
    – Daniel Hinojosa
    Nov 11 at 19:57










  • Ah yeah, didn't know about Akka Streams. Though (from a first impression only) their DSL is slightly uglier than what's possible in Kotlin, so I suppose the bottom line is that the DSL I made in Kotlin is probably not possible to exactly reproduce in Scala, at least as an embedded DSL. It's good to have found that out now, at least.
    – Tagc
    Nov 11 at 20:07










  • @TagC From what I understand Kotlin doesn't have type classes. github.com/Kotlin/KEEP/pull/87 and that having that power is great to have in Scala. My guess is that if Kotlin would need to make TypeClasses a thing it would have to look like Scala where we have control of our import and implicit, or in Kotlin's case extension. But I am answering out of ignorance of Kotlin since I am not a professional with Kotlin. ;)
    – Daniel Hinojosa
    Nov 11 at 20:12

















up vote
1
down vote













Just turning on the |> is pretty straightforward in Scala if you use a companion object, and is something always available with the output port



class OutputPort[-A] {
def connectTo(inputPort: InputPort[A]):Unit = {}
}

class InputPort[+A]

object OutputPort{
implicit class ConnectablePort[A](outputPort: OutputPort[A]) {
def |>(inputPort: InputPort[A]): Unit = outputPort connectTo inputPort
}
}

def someCompositeFunction() {
val output = new OutputPort[Int]
val input = new InputPort[Int]
output |> input // Should be valid here
}


Judiciously deciding where to do imports is a core Scala concept. It is how we turn on implicit in our code, like the following, is very common, since that is the way we turn on our type classes.



class OutputPort[-A] {
def connectTo(inputPort: InputPort[A]): Unit = {}
}

class InputPort[+A]

object Converter {
implicit class ConnectablePort[A](outputPort: OutputPort[A]) {
def |>(inputPort: InputPort[A]): Unit = outputPort connectTo inputPort
}
}

def someCompositeFunction() {
val output = new OutputPort[Int]
val input = new InputPort[Int]
import Converter._
output |> input // Should be valid here
}


Now, I think this is what you are looking for, but there are still some import and implicit that needs to be setup, but this would enclose the implicit behavior:



class OutputPort[-A] {
def connectTo(inputPort: InputPort[A]): Unit = {}
}

class InputPort[+A]

object Converter {

private class ConnectablePort[A](outputPort: OutputPort[A]) {
def |>(inputPort: InputPort[A]): Unit = outputPort connectTo
inputPort
}

def convert[A](f: (OutputPort[A] => ConnectablePort[A]) => Unit): Unit = {
def connectablePortWrapper(x: OutputPort[A]): ConnectablePort[A] = new ConnectablePort[A](x)

f(connectablePortWrapper _)
}
}

object MyRunner extends App {

val output = new OutputPort[Int]
val input = new InputPort[Int]

import Converter.convert

//output |> input won't work
convert[Int] { implicit wrapper =>
output |> input // Should be valid here
}
}





share|improve this answer























  • Upvoting for the effort put in and the helpful tips, but that DSL at the bottom does not look very nice compared to the Kotlin equivalent - it involves import statements, and implicit parameters that aren't used. Additionally, the block where I wire up the connections shouldn't be parameterised as the idea is that only the types for each individual connection between two ports need to match, not every connection defined within the block. I'm trying to get something as close as possible to the addAndSquare example.
    – Tagc
    Nov 11 at 19:52












  • You're right that I can make |> always available using a companion object - I've updated my post with a less-contrived example in which |> is more than just an alternative of connectTo, and therefore why it might be something I only want to be available within a particular scope. For what it's worth, the Akka DSL looks to be doing a similar kind of thing to what I'm after, but I'm still trying to understand how they do it.
    – Tagc
    Nov 11 at 19:54






  • 1




    Akka DSL and Akka Streams DSL would be a great way to find examples of what you're looking for. :)
    – Daniel Hinojosa
    Nov 11 at 19:57










  • Ah yeah, didn't know about Akka Streams. Though (from a first impression only) their DSL is slightly uglier than what's possible in Kotlin, so I suppose the bottom line is that the DSL I made in Kotlin is probably not possible to exactly reproduce in Scala, at least as an embedded DSL. It's good to have found that out now, at least.
    – Tagc
    Nov 11 at 20:07










  • @TagC From what I understand Kotlin doesn't have type classes. github.com/Kotlin/KEEP/pull/87 and that having that power is great to have in Scala. My guess is that if Kotlin would need to make TypeClasses a thing it would have to look like Scala where we have control of our import and implicit, or in Kotlin's case extension. But I am answering out of ignorance of Kotlin since I am not a professional with Kotlin. ;)
    – Daniel Hinojosa
    Nov 11 at 20:12















up vote
1
down vote










up vote
1
down vote









Just turning on the |> is pretty straightforward in Scala if you use a companion object, and is something always available with the output port



class OutputPort[-A] {
def connectTo(inputPort: InputPort[A]):Unit = {}
}

class InputPort[+A]

object OutputPort{
implicit class ConnectablePort[A](outputPort: OutputPort[A]) {
def |>(inputPort: InputPort[A]): Unit = outputPort connectTo inputPort
}
}

def someCompositeFunction() {
val output = new OutputPort[Int]
val input = new InputPort[Int]
output |> input // Should be valid here
}


Judiciously deciding where to do imports is a core Scala concept. It is how we turn on implicit in our code, like the following, is very common, since that is the way we turn on our type classes.



class OutputPort[-A] {
def connectTo(inputPort: InputPort[A]): Unit = {}
}

class InputPort[+A]

object Converter {
implicit class ConnectablePort[A](outputPort: OutputPort[A]) {
def |>(inputPort: InputPort[A]): Unit = outputPort connectTo inputPort
}
}

def someCompositeFunction() {
val output = new OutputPort[Int]
val input = new InputPort[Int]
import Converter._
output |> input // Should be valid here
}


Now, I think this is what you are looking for, but there are still some import and implicit that needs to be setup, but this would enclose the implicit behavior:



class OutputPort[-A] {
def connectTo(inputPort: InputPort[A]): Unit = {}
}

class InputPort[+A]

object Converter {

private class ConnectablePort[A](outputPort: OutputPort[A]) {
def |>(inputPort: InputPort[A]): Unit = outputPort connectTo
inputPort
}

def convert[A](f: (OutputPort[A] => ConnectablePort[A]) => Unit): Unit = {
def connectablePortWrapper(x: OutputPort[A]): ConnectablePort[A] = new ConnectablePort[A](x)

f(connectablePortWrapper _)
}
}

object MyRunner extends App {

val output = new OutputPort[Int]
val input = new InputPort[Int]

import Converter.convert

//output |> input won't work
convert[Int] { implicit wrapper =>
output |> input // Should be valid here
}
}





share|improve this answer














Just turning on the |> is pretty straightforward in Scala if you use a companion object, and is something always available with the output port



class OutputPort[-A] {
def connectTo(inputPort: InputPort[A]):Unit = {}
}

class InputPort[+A]

object OutputPort{
implicit class ConnectablePort[A](outputPort: OutputPort[A]) {
def |>(inputPort: InputPort[A]): Unit = outputPort connectTo inputPort
}
}

def someCompositeFunction() {
val output = new OutputPort[Int]
val input = new InputPort[Int]
output |> input // Should be valid here
}


Judiciously deciding where to do imports is a core Scala concept. It is how we turn on implicit in our code, like the following, is very common, since that is the way we turn on our type classes.



class OutputPort[-A] {
def connectTo(inputPort: InputPort[A]): Unit = {}
}

class InputPort[+A]

object Converter {
implicit class ConnectablePort[A](outputPort: OutputPort[A]) {
def |>(inputPort: InputPort[A]): Unit = outputPort connectTo inputPort
}
}

def someCompositeFunction() {
val output = new OutputPort[Int]
val input = new InputPort[Int]
import Converter._
output |> input // Should be valid here
}


Now, I think this is what you are looking for, but there are still some import and implicit that needs to be setup, but this would enclose the implicit behavior:



class OutputPort[-A] {
def connectTo(inputPort: InputPort[A]): Unit = {}
}

class InputPort[+A]

object Converter {

private class ConnectablePort[A](outputPort: OutputPort[A]) {
def |>(inputPort: InputPort[A]): Unit = outputPort connectTo
inputPort
}

def convert[A](f: (OutputPort[A] => ConnectablePort[A]) => Unit): Unit = {
def connectablePortWrapper(x: OutputPort[A]): ConnectablePort[A] = new ConnectablePort[A](x)

f(connectablePortWrapper _)
}
}

object MyRunner extends App {

val output = new OutputPort[Int]
val input = new InputPort[Int]

import Converter.convert

//output |> input won't work
convert[Int] { implicit wrapper =>
output |> input // Should be valid here
}
}






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 11 at 18:21

























answered Nov 11 at 17:13









Daniel Hinojosa

83458




83458












  • Upvoting for the effort put in and the helpful tips, but that DSL at the bottom does not look very nice compared to the Kotlin equivalent - it involves import statements, and implicit parameters that aren't used. Additionally, the block where I wire up the connections shouldn't be parameterised as the idea is that only the types for each individual connection between two ports need to match, not every connection defined within the block. I'm trying to get something as close as possible to the addAndSquare example.
    – Tagc
    Nov 11 at 19:52












  • You're right that I can make |> always available using a companion object - I've updated my post with a less-contrived example in which |> is more than just an alternative of connectTo, and therefore why it might be something I only want to be available within a particular scope. For what it's worth, the Akka DSL looks to be doing a similar kind of thing to what I'm after, but I'm still trying to understand how they do it.
    – Tagc
    Nov 11 at 19:54






  • 1




    Akka DSL and Akka Streams DSL would be a great way to find examples of what you're looking for. :)
    – Daniel Hinojosa
    Nov 11 at 19:57










  • Ah yeah, didn't know about Akka Streams. Though (from a first impression only) their DSL is slightly uglier than what's possible in Kotlin, so I suppose the bottom line is that the DSL I made in Kotlin is probably not possible to exactly reproduce in Scala, at least as an embedded DSL. It's good to have found that out now, at least.
    – Tagc
    Nov 11 at 20:07










  • @TagC From what I understand Kotlin doesn't have type classes. github.com/Kotlin/KEEP/pull/87 and that having that power is great to have in Scala. My guess is that if Kotlin would need to make TypeClasses a thing it would have to look like Scala where we have control of our import and implicit, or in Kotlin's case extension. But I am answering out of ignorance of Kotlin since I am not a professional with Kotlin. ;)
    – Daniel Hinojosa
    Nov 11 at 20:12




















  • Upvoting for the effort put in and the helpful tips, but that DSL at the bottom does not look very nice compared to the Kotlin equivalent - it involves import statements, and implicit parameters that aren't used. Additionally, the block where I wire up the connections shouldn't be parameterised as the idea is that only the types for each individual connection between two ports need to match, not every connection defined within the block. I'm trying to get something as close as possible to the addAndSquare example.
    – Tagc
    Nov 11 at 19:52












  • You're right that I can make |> always available using a companion object - I've updated my post with a less-contrived example in which |> is more than just an alternative of connectTo, and therefore why it might be something I only want to be available within a particular scope. For what it's worth, the Akka DSL looks to be doing a similar kind of thing to what I'm after, but I'm still trying to understand how they do it.
    – Tagc
    Nov 11 at 19:54






  • 1




    Akka DSL and Akka Streams DSL would be a great way to find examples of what you're looking for. :)
    – Daniel Hinojosa
    Nov 11 at 19:57










  • Ah yeah, didn't know about Akka Streams. Though (from a first impression only) their DSL is slightly uglier than what's possible in Kotlin, so I suppose the bottom line is that the DSL I made in Kotlin is probably not possible to exactly reproduce in Scala, at least as an embedded DSL. It's good to have found that out now, at least.
    – Tagc
    Nov 11 at 20:07










  • @TagC From what I understand Kotlin doesn't have type classes. github.com/Kotlin/KEEP/pull/87 and that having that power is great to have in Scala. My guess is that if Kotlin would need to make TypeClasses a thing it would have to look like Scala where we have control of our import and implicit, or in Kotlin's case extension. But I am answering out of ignorance of Kotlin since I am not a professional with Kotlin. ;)
    – Daniel Hinojosa
    Nov 11 at 20:12


















Upvoting for the effort put in and the helpful tips, but that DSL at the bottom does not look very nice compared to the Kotlin equivalent - it involves import statements, and implicit parameters that aren't used. Additionally, the block where I wire up the connections shouldn't be parameterised as the idea is that only the types for each individual connection between two ports need to match, not every connection defined within the block. I'm trying to get something as close as possible to the addAndSquare example.
– Tagc
Nov 11 at 19:52






Upvoting for the effort put in and the helpful tips, but that DSL at the bottom does not look very nice compared to the Kotlin equivalent - it involves import statements, and implicit parameters that aren't used. Additionally, the block where I wire up the connections shouldn't be parameterised as the idea is that only the types for each individual connection between two ports need to match, not every connection defined within the block. I'm trying to get something as close as possible to the addAndSquare example.
– Tagc
Nov 11 at 19:52














You're right that I can make |> always available using a companion object - I've updated my post with a less-contrived example in which |> is more than just an alternative of connectTo, and therefore why it might be something I only want to be available within a particular scope. For what it's worth, the Akka DSL looks to be doing a similar kind of thing to what I'm after, but I'm still trying to understand how they do it.
– Tagc
Nov 11 at 19:54




You're right that I can make |> always available using a companion object - I've updated my post with a less-contrived example in which |> is more than just an alternative of connectTo, and therefore why it might be something I only want to be available within a particular scope. For what it's worth, the Akka DSL looks to be doing a similar kind of thing to what I'm after, but I'm still trying to understand how they do it.
– Tagc
Nov 11 at 19:54




1




1




Akka DSL and Akka Streams DSL would be a great way to find examples of what you're looking for. :)
– Daniel Hinojosa
Nov 11 at 19:57




Akka DSL and Akka Streams DSL would be a great way to find examples of what you're looking for. :)
– Daniel Hinojosa
Nov 11 at 19:57












Ah yeah, didn't know about Akka Streams. Though (from a first impression only) their DSL is slightly uglier than what's possible in Kotlin, so I suppose the bottom line is that the DSL I made in Kotlin is probably not possible to exactly reproduce in Scala, at least as an embedded DSL. It's good to have found that out now, at least.
– Tagc
Nov 11 at 20:07




Ah yeah, didn't know about Akka Streams. Though (from a first impression only) their DSL is slightly uglier than what's possible in Kotlin, so I suppose the bottom line is that the DSL I made in Kotlin is probably not possible to exactly reproduce in Scala, at least as an embedded DSL. It's good to have found that out now, at least.
– Tagc
Nov 11 at 20:07












@TagC From what I understand Kotlin doesn't have type classes. github.com/Kotlin/KEEP/pull/87 and that having that power is great to have in Scala. My guess is that if Kotlin would need to make TypeClasses a thing it would have to look like Scala where we have control of our import and implicit, or in Kotlin's case extension. But I am answering out of ignorance of Kotlin since I am not a professional with Kotlin. ;)
– Daniel Hinojosa
Nov 11 at 20:12






@TagC From what I understand Kotlin doesn't have type classes. github.com/Kotlin/KEEP/pull/87 and that having that power is great to have in Scala. My guess is that if Kotlin would need to make TypeClasses a thing it would have to look like Scala where we have control of our import and implicit, or in Kotlin's case extension. But I am answering out of ignorance of Kotlin since I am not a professional with Kotlin. ;)
– Daniel Hinojosa
Nov 11 at 20:12




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53248121%2fhow-can-i-create-a-dsl-involving-blocks-where-certain-functions-are-in-scope%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

鏡平學校

ꓛꓣだゔៀៅຸ໢ທຮ໕໒ ,ໂ'໥໓າ໼ឨឲ៵៭ៈゎゔit''䖳𥁄卿' ☨₤₨こゎもょの;ꜹꟚꞖꞵꟅꞛေၦေɯ,ɨɡ𛃵𛁹ޝ޳ޠ޾,ޤޒޯ޾𫝒𫠁သ𛅤チョ'サノބޘދ𛁐ᶿᶇᶀᶋᶠ㨑㽹⻮ꧬ꧹؍۩وَؠ㇕㇃㇪ ㇦㇋㇋ṜẰᵡᴠ 軌ᵕ搜۳ٰޗޮ޷ސޯ𫖾𫅀ल, ꙭ꙰ꚅꙁꚊꞻꝔ꟠Ꝭㄤﺟޱސꧨꧼ꧴ꧯꧽ꧲ꧯ'⽹⽭⾁⿞⼳⽋២៩ញណើꩯꩤ꩸ꩮᶻᶺᶧᶂ𫳲𫪭𬸄𫵰𬖩𬫣𬊉ၲ𛅬㕦䬺𫝌𫝼,,𫟖𫞽ហៅ஫㆔ాఆఅꙒꚞꙍ,Ꙟ꙱エ ,ポテ,フࢰࢯ𫟠𫞶 𫝤𫟠ﺕﹱﻜﻣ𪵕𪭸𪻆𪾩𫔷ġ,ŧآꞪ꟥,ꞔꝻ♚☹⛵𛀌ꬷꭞȄƁƪƬșƦǙǗdžƝǯǧⱦⱰꓕꓢႋ神 ဴ၀க௭எ௫ឫោ ' េㇷㇴㇼ神ㇸㇲㇽㇴㇼㇻㇸ'ㇸㇿㇸㇹㇰㆣꓚꓤ₡₧ ㄨㄟ㄂ㄖㄎ໗ツڒذ₶।ऩछएोञयूटक़कयँृी,冬'𛅢𛅥ㇱㇵㇶ𥄥𦒽𠣧𠊓𧢖𥞘𩔋цѰㄠſtʯʭɿʆʗʍʩɷɛ,əʏダヵㄐㄘR{gỚṖḺờṠṫảḙḭᴮᵏᴘᵀᵷᵕᴜᴏᵾq﮲ﲿﴽﭙ軌ﰬﶚﶧ﫲Ҝжюїкӈㇴffצּ﬘﭅﬈軌'ffistfflſtffतभफɳɰʊɲʎ𛁱𛁖𛁮𛀉 𛂯𛀞నఋŀŲ 𫟲𫠖𫞺ຆຆ ໹້໕໗ๆทԊꧢꧠ꧰ꓱ⿝⼑ŎḬẃẖỐẅ ,ờỰỈỗﮊDžȩꭏꭎꬻ꭮ꬿꭖꭥꭅ㇭神 ⾈ꓵꓑ⺄㄄ㄪㄙㄅㄇstA۵䞽ॶ𫞑𫝄㇉㇇゜軌𩜛𩳠Jﻺ‚Üမ႕ႌႊၐၸဓၞၞၡ៸wyvtᶎᶪᶹစဎ꣡꣰꣢꣤ٗ؋لㇳㇾㇻㇱ㆐㆔,,㆟Ⱶヤマފ޼ޝަݿݞݠݷݐ',ݘ,ݪݙݵ𬝉𬜁𫝨𫞘くせぉて¼óû×ó£…𛅑הㄙくԗԀ5606神45,神796'𪤻𫞧ꓐ㄁ㄘɥɺꓵꓲ3''7034׉ⱦⱠˆ“𫝋ȍ,ꩲ軌꩷ꩶꩧꩫఞ۔فڱێظペサ神ナᴦᵑ47 9238їﻂ䐊䔉㠸﬎ffiﬣ,לּᴷᴦᵛᵽ,ᴨᵤ ᵸᵥᴗᵈꚏꚉꚟ⻆rtǟƴ𬎎

Why https connections are so slow when debugging (stepping over) in Java?