is it possible to make `val x: Stack<String>...
# announcements
m
is it possible to make
val x: Stack<String> = "a"
auto convert to
return Stack("a")
via some function without needing to explicitly state
val x = Stack<String>("a")
s
No, Kotlin’s type inference can’t do something quite this, uh, advanced
m
oh
s
I imagine there’s a fair bit of ambiguity there that the language designers would like to avoid
that said, I mean,
Copy code
val x = Stack("a")
is pretty concise, no?
(assuming that the constructor takes
T
anyhow)
m
ok, then would it be possible to do the same for a paramater like assuming
Copy code
fun makeStack(s: Stack): Stack = s
transform
Copy code
fun makeStack("a")
to
Copy code
makeStack(Stack("a"))
or would that also be impossible
assuming it is meant to ONLY take a single type
via some magic function that could take a function to apply to given paramater
as i want to make it so that instead of doing this
Copy code
val A = IsSequenceOneOrMany("A")
val B = IsSequenceOneOrMany("B")
val AB = A and B
i can do this instead
Copy code
val AB: IsSequenceOneOrMany = "A" and "B"
so it looks more natural
s
So, you can actually implement that exact syntax
but I would strongly recommend scoping the code you add to a certain class or otherwise narrow context
like a builder or part of a DSL
the code itself would look like this:
Copy code
infix fun String.and(other: String) = IsSequenceOneOrMany(this) and IsSequenceOneOrMany(other)
but that really probably shouldn’t be top-level
m
ok, how would i accomplish so
s
probably within a class’s companion object or top-level private if you want it in a specific file
m
could you give me an example of how that would work?
as i assume, for X class,
X("string1" and "string2")
and
val str = "string1" and "string2"
will each invoke different
String.and
functions right?
assuming
scoping the code you add to a certain class
means that for example, function extentions for String will only be applied when given as a parameter for desired class or something similar
s
that’s not quite how that works - the area inside parenthesis does not constitute a different scope
what I’m describing looks maybe more like this:
Copy code
val xInstance = buildX {
  someField = "string1" and "string2"
}
m
ok, how would i... construct such a function
k
I'm scared to even give you this link, but see https://kotlinlang.org/docs/reference/type-safe-builders.html
👆 1
🔥 1
w
Another example could be:
Copy code
data class MyClass(val value: String)
    
    val String.parse: MyClass
        get() = MyClass(this)

    @Test
    fun asas() {
        
        fun asas(myClass: MyClass): Unit = TODO()
        asas("a".parse)

        val x: MyClass = "a".parse

    }