https://kotlinlang.org logo
Title
s

scottiedog45

10/22/2019, 5:03 PM
Is there a way to initialize an object from a primitive type? Something like
data class Foo(val a: String) {
    
    init {
        //magic that takes string and sets it to a
    }
}

var Bar : Foo = "b"
s

Shawn

10/22/2019, 5:06 PM
No. Generally speaking, Kotlin avoids this kind of implicit behavior
maybe consider an extension function?
fun String.asFoo() = Foo(this)

val bar = "b".asFoo()
it’s maybe not as concise as just calling the constructor, but maybe it fits better in your code, stylistically speaking
s

scottiedog45

10/22/2019, 5:09 PM
Yeah it makes sense - I’ve seen something analogous in Swift so I was wondering if I was missing out on a language feature thanks for the tip and recommendation 😃
👍 1
s

Shawn

10/22/2019, 5:11 PM
You also might consider just using a typealias, though that wouldn’t have the same type safety as
ExpressibleByStringLiteral
s

scottiedog45

10/22/2019, 5:16 PM
interesting. I’m not seeing how typealias helps here, would you have a quick example?
s

Shawn

10/22/2019, 5:26 PM
I just mean in the case where you literally only want a better name for your String usage - if your string-containing data class has other functionality, then you’re right that a typealias won’t help
s

scottiedog45

10/22/2019, 5:27 PM
aah got it thanks 😁
💯 1