是否可以在kotlin中使用unaryPlus调用函数? [英] Is it possible to invoke a function with a unaryPlus in kotlin?

查看:136
本文介绍了是否可以在kotlin中使用unaryPlus调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我昨天问的另一个问题的后续问题.

This is a followup question on another question I asked yesterday.

如何使用构建器构建嵌套列表模式?

由于提供了很好的答案,请致谢:佩洛乔.

Credit to: Pelocho for giving nice answer.

我使用本教程进行类型安全的graphQL查询建造者:

I used this Tutorial to do a type safe graphQL query builder:

我现在想做的就是简化我所做的事情 而且我知道kotlin必须具有一些不错的功能才能做到这一点.

What I want to do now is to simplify what I made And I know that kotlin must have some nice features to do that.

现在,当我想向查询中添加实体时,我必须调用函数:

Right now I have to invoke functions when I want to add an entity to my query:

fun main() {
    events{
        title() // I don't like to do () when it is an edge case
    }
}

我想知道是否可以做一些不同的,更简单的事情,例如:

I am wondering if it is posible to do something different, and more simple, like:

fun main() {
    events{
        title // this is much nicer
    }
}

但是如果不可能的话,可以通过操作符重载来减少字符数,例如. unaryPlus

But if it is not possible then it is ok just to reduce the amount of characters with an operator overloading like eg. unaryPlus

fun main() {
    events{
        +title // this is also nicer
    }
}

我现在拥有的代码有一个名为Query的类,在其中放置了方法:

My code that I have now has a class called Query where I put the method:

    operator fun Query.unaryPlus() {
        visitEntity(this,{})
    }

但是它似乎对我不起作用.

But it does not seem to work for me.

我所有的代码都在这里.

All my code is here.

interface Element {
    fun render(builder: StringBuilder, indent: String)
}

@DslMarker //Domain Specific Language
annotation class GraphQLMarker


@GraphQLMarker
abstract class Query(val name: String) : Element {
    val children = arrayListOf<Element>()
    protected fun <T : Element> visitEntity(entity: T, visit: T.() -> Unit = {}): T {
        entity.visit()
        children.add(entity)
        return entity
    }

    override fun render(builder: StringBuilder, indent: String) {
        builder.append("$indent$name")
        if (children.isNotEmpty()) {
            builder.append("{\n")
            for (c in children) {
                c.render(builder, "$indent  ")
            }
            builder.append("$indent}")
        }
        builder.append("\n")
    }

    operator fun Query.unaryPlus() {
        visitEntity(this,{})
    }

    override fun toString(): String {
        val builder = StringBuilder()
        render(builder, "")
        return builder.toString()
    }
}

然后我创建了与我的案例相关的类

Then I created the classes relevant to my case


class Filter private constructor(val filters: MutableMap<FilterType, Any>) {
    class Builder {
        private val filters = mutableMapOf<FilterType, Any>()
        fun filters(key: FilterType, value: Any) = apply {
            this.filters[key] = value
        }

        fun build(): Filter {
            return Filter(filters)
        }
    }
}

class EVENTS(private val filter: Filter) : Query("events") {
    override fun render(builder: StringBuilder, indent: String) {
        builder.append("{$name")
        if (filter.filters.isNotEmpty()) {
            builder.append("(" + filter.filters.map {
                if (it.value is Int || it.value is Long) {
                    it.key.str + ":" + it.value + ","
                } else {
                    it.key.str + ":\"" + it.value + "\","
                }
            }.joinToString(" ").dropLast(1) + ")")
        }
        if (children.isNotEmpty()) {
            builder.append("{\n")
            for (c in children) {
                c.render(builder, "$indent  ")
            }
            builder.append("$indent}")
        }
        builder.append("\n}")
    }

    fun title() = visitEntity(TITLE())
    fun genre() = visitEntity(GENRE())
    fun image() = visitEntity(IMAGE())
    fun link() = visitEntity(LINK())
    fun other() = visitEntity(OTHER())
    fun price() = visitEntity(PRICE())
    fun text() = visitEntity(TEXT())
    fun tickets() = visitEntity(TICKETS())
    fun time() = visitEntity(TIME())
    fun location(visit: LOCATION.() -> Unit) = visitEntity(LOCATION(), visit)
}

class TITLE : Query("title")
class GENRE : Query("genre")
class IMAGE : Query("image")
class LINK : Query("link")
class OTHER : Query("other")
class PRICE : Query("price")
class TEXT : Query("text")
class TICKETS : Query("tickets")
class TIME : Query("time")
class LOCATION : Query("location") {
    fun area() = visitEntity(AREA())
    fun place() = visitEntity(PLACE())
    fun address(visit: ADDRESS.() -> Unit) = visitEntity(ADDRESS(), visit)
    fun coordinates(visit: COORDINATES.() -> Unit) = visitEntity(COORDINATES(), visit)
}

class AREA : Query("area")
class PLACE : Query("place")
class ADDRESS : Query("address") {
    fun city() = visitEntity(CITY())
    fun street() = visitEntity(STREET())
    fun no() = visitEntity(NO())
    fun state() = visitEntity(STATE())
    fun zip() = visitEntity(ZIP())
}

class CITY : Query("city")
class STREET : Query("street")
class NO : Query("no")
class STATE : Query("state")
class ZIP : Query("zip")
class COORDINATES : Query("coordinates") {
    fun longitude() = visitEntity(LONGITUDE())
    fun latitude() = visitEntity(LATITUDE())
}

class LONGITUDE : Query("longitude")
class LATITUDE : Query("latitude")

enum class FilterType(val str: String) {
    PLACE("place"),
    PRICELT("priceLT"),
    PRICEGT("priceGT"),
    TIMELT("timestampLT"),
    TIMEGT("timestampGT"),
    AREA("area"),
    TITLE("title"),
    GENRE("genre")
}

其中一些类别是 edgecases ,因此不会将它们嵌套得更深.所以我在想是否可以简化一下.而且,当我从main()函数调用它们时,如果可以使用unaryPlus来调用它们,那么当它们没有嵌套的任何等待时,我就不必在非常单一的边缘情况下编写{}

Some of the classes are edgecases and will not nest themself further down. So I was thinking if it is possible to simplify that a bit. And if I can use a unaryPlus to invoke them when I call them from the main() function, so I dont have to write {} after very single edgecase, when they dont have nesting anywaits

fun main(){
    events(filter) {
        title()
        genre()
        image()
        link()
        tickets()
        other()
        price()
        text()
        time()
        location {
            area()
            place()
            address {
                city()
                street()
                no()
                state()
                zip()
            }
            coordinates {
                longitude()
                latitude()
            }
        }
    }
}

先谢谢您.祝你有美好的一天!

Thank you in advance. Have a nice day!

推荐答案

是的,您可以根据需要使用unaryPlus

Yes, you can use unaryPlus for whatever you want

查看操作员重载文档

这里有一个有效的示例:

Here you have a working example:

fun main() {
    val events = events {
        +title
        +genre
    }

    println(events.render())
}

interface Element {
    fun render() : String
}

@DslMarker //Domain Specific Language
annotation class GraphQLMarker

@GraphQLMarker
fun events(init: EventBody.() -> Unit): Element {
    val events = EventBody()
    events.init()
    return events
}


class EventBody: Element {
    override fun render() =
        "events:${elements.joinToString { it.render() }}"

    private val elements = mutableListOf<Element>()

    operator fun Element.unaryPlus() = elements.add(this)
}

@GraphQLMarker
object title: Element {
    override fun render() = "title"
}

@GraphQLMarker
object genre: Element {
    override fun render() = "genre"
}

输出

events:title, genre

这篇关于是否可以在kotlin中使用unaryPlus调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆