Jorrit
08/05/2020, 12:54 AMdata class Test(val i: Int, val s: String)
var t = Test(1, "hello")
someJavascriptFunctionExpectingObject(t)
var t = js("{i: 1, s: 'hello'}").unsafeCase<Test>()
In hindsight it seems obvious that this works. But when Googling around for this I ran into all sorts of parsers and lengthy code ending up with the same thing but significantly slower. Is there something wrong with doing it this way, other than losing presence/type checks for the fields? Is this likely to break in unexpected ways (such as?) or is it fine to use in tightly controlled cases?
Thank you for coming to my TED talk 🙂andylamax
08/05/2020, 1:39 AMdata class Test
is a kotlin class meaning it has constructors,copy(), toString() equals and hashcode()
while js("{i: 1, s: 'helo'}")
is just a plain javascript object.
unsafeCast<Test>()
tells the compiler to completely ignore the underlying data type and just pretend it is an object of class Test
while this succeeds, the operation is not safe as the name suggests.
in short. The only similarity in the two object, is that they appear to have the same property names.
FYI, also js("{i:"1", s: 40}").unsafeCast<Test>()
would work.
val test1 = js("{i: 1, s:'hello'}")
console.log(test1.i) // might work (name mangling)
console.log(test1.s) // might work
console.log(test1.i + 1) // might work
console.log(test1.copy(i=5)) // error
console.log(Test(1,"hello")==test) // false
val test2 = js("{i: 'One', s:'hello'}")
console.log(test2.i) // might work
console.log(test2.s) // might work
console.log(test2.i + 1) // undefined
console.log(test2.copy(i=5)) // error
console.log(Test(1,"hello")==test) // false (as expected)
Jorrit
08/05/2020, 9:00 AMandylamax
08/05/2020, 9:47 AMunsafeCast()
doesn't do deep copy at all. you can check its imolementation.
How ever, a deep copy method provided by the kotlin std lib, would be greatJorrit
08/05/2020, 10:20 AM