why doesn't "is" operator honor inheritance in kotlinjs - kotlin

I'm developing a kotlinjs react project.
plugins {
kotlin("js") version "1.8.0"
}
and I've written this class:
class Percentage(private val number: Number) : Number() {
override fun toByte() = number.toByte()
override fun toChar() = number.toChar()
override fun toDouble() = number.toDouble()
override fun toFloat() = number.toFloat()
override fun toInt() = number.toInt()
override fun toLong() = number.toLong()
override fun toShort() = number.toShort()
override fun toString() = "$number%"
}
but is operator seems not to honor inheritance:
if (value is Percentage) {
println(value is Number)
}
even IDEA warns me that "check for instance is always true" yet console prints false...

So I check the generated JS code, and see this:
function isNumber(a_28) {
var tmp_349;
if (typeof a_28 === 'number') {
tmp_349 = true;
} else {
tmp_349 = a_28 instanceof Long;
}
return tmp_349;
}
function main() {
var value_70 = new Percentage(42);
if (value_70 instanceof Percentage) {
println(isNumber(value_70));
}
}
which explains everything. The is operator behavior is inconsistent around primitive type like Number, because of Kotlin/JS language difference.

Related

Is it possible to verify at compile time whether the required function is called for the Factory Class in Kotlin?

class ModelFactory {
fun setA() : ModelFactory {
// blabla...
}
fun setB() : ModelFactory {
// blabla...
}
fun setC() : ModelFactory {
// blabla...
}
fun build() : Model {
// An error occurs if any of setA, setB, and setC is not called.
}
}
//example
fun successTest() {
ModelFactory().setA().setB().setC().build() // No error occurs at compile time
}
fun failTest() {
ModelFactory().setA().build() // An error occurs at compile time because setB and setC are not called.
}
It's awkward grammatically, but I think it's been expressed what I want.
I have already implemented an error-raising runtime for this requirement, but I want to check this at compile time.
If possible, I think I should use annotations. But is this really possible at compile time?
With Kotlin, I have been avoiding builder pattern, as we can always specify default values for non-mandatory fields.
If you still want to use a builder pattern, you can use Step builder pattern that expects all mandatory fields to be set before creating the object. Note that each setter method returns the reference of next setter interface. You can have multiple Step builders based on the combination of mandatory fields.
class Model(val a: String = "", val b: String = "", val c: String = "")
class StepBuilder {
companion object {
fun builder(): AStep = Steps()
}
interface AStep {
fun setA(a: String): BStep
}
interface BStep {
fun setB(b: String): CStep
}
interface CStep {
fun setC(c: String): BuildStep
}
interface BuildStep {
//fun setOptionalField(x: String): BuildStep
fun build(): Model
}
class Steps : AStep, BStep, CStep, BuildStep {
private lateinit var a: String
private lateinit var b: String
private lateinit var c: String
override fun setA(a: String): BStep {
this.a = a
return this
}
override fun setB(b: String): CStep {
this.b = b
return this
}
override fun setC(c: String): BuildStep {
this.c = c
return this
}
override fun build() = Model(a, b , c)
}
}
fun main() {
// cannot build until you call all three setters
val model = StepBuilder.builder().setA("A").setB("B").setC("C").build()
}

Using lambdas does not compile when trying to pass in a method expecting a SAM interface

I am trying to understand lambdas and Kotlin. I created this trivial example
interface OnClickListener {
fun onClick(s: String)
}
class Button {
var clickListener: OnClickListener? = null
fun setOnClickListener(listener: OnClickListener?) {
clickListener = listener
}
fun click() {
clickListener?.onClick("hello")
}
}
fun main(args: Array<String>) {
val b = Button()
b.setOnClickListener(
object : OnClickListener {
override fun onClick(s: String) {
println(s)
}
}
)
/*
Variation 1
val l = {
s -> println(s)
}
b.clickListener = l*/
/*
Variation 2
b.setOnClickListener{
s -> println(s)
}
*/
/*
Variation 3
b.clickListener = {
s -> println(s)
}
*/
b.click()
}
So the above code only compiles if I pass an anonymous object. But I wanted to figure out how to use the lambdas.
None of the 3 variation to use a lambda compiles.
I thought since the OnClickListener is a SAM I should easily be able to pass in a lambda
What am I doing wrong here?
To be able to use a lambda, you need to use a Java interface.
First, create a Java file and create an interface:
public interface OnClickListener {
void onClick(String s);
}
Then in your main:
b.setOnClickListener(OnClickListener { s ->
println(s)
})
As for your Button class:
class Button {
var clickListener: OnClickListener? = null //You can use this too but there's another way as well.
//lateinit var clickListener: OnClickListener //Telling the compiler that you will initialize it later on.
fun setOnClickListener(listener: OnClickListener) { //removed redundant ? from the function signature.
clickListener = listener
}
fun click() {
clickListener?.onClick("hello") //Incase of lateinit, you don't need a '?' anymore
}
}
SAM conversion only works between a Java code and a Kotlin code.
EDIT: Since in Kotlin, you can store a function in a variable as well, here is my another two cents on how you can do it in a different way:
class Button {
lateinit var myFunction: (String) -> Unit
fun setOnClickListener(block : (String) -> Unit) {
myFunction = block //storing state of your 'listener'
}
fun onClick() = myFunction.invoke("Invoked from onClick function")
}
Then in your main:
fun main() {
val button = Button()
button.setOnClickListener { s ->
println(s)
}
button.onClick()
}
As Taseer Ahmad points out, SAM conversion only works for Java interfaces since Kotlin already has proper function types. Of course, an easy way around this is to simply define a second setOnClickListener method that takes a function type
class Button {
var clickListener: OnClickListener? = null
fun setOnClickListener(listener: OnClickListener?) {
clickListener = listener
}
inline fun setOnClickListener(crossinline listener: (String) -> Unit) {
setOnClickListener(object : OnClickListener {
override fun onClick(s: String) = listener(s)
})
}
fun click() {
clickListener?.onClick("hello")
}
}
This then allows you to write b.setOnClickListener { println(it) }. I always inline methods like this as a habit, but it's not really required, so you can remove the inline and crossinline if you want.

Binding custom data type transmit null to converter

I'm using Jooq and Kotlin in my project. I have object EventEnvelope in which field of type Event is composed. I want to store this field as JSON in my DB (postgres). I prepared jooq custom datatype bindings and converter as it is described here -> https://www.jooq.org/doc/3.10/manual/code-generation/custom-data-type-bindings/
Below I paste converter, binding and gradle generator code.
My questions are:
Is it ok to use kotlin non null types with jooq bindings?
Is this configuration ok? What should I change?
When I want to store value my converter gets null in from func. I don't why is that.
I am out of ideas what should I do to fix it.
class JSONEventConverter constructor(
private val objectMapper: ObjectMapper,
private val schemaMatcher: SchemaMatcher
) : Converter<Any, Event> {
override fun from(databaseObject: Any): Event {
return schemaMatcher.parse(databaseObject.toString())
}
override fun to(userObject: Event): Any {
return objectMapper.writeValueAsString(userObject)
}
override fun fromType(): Class<Any> {
return Any::class.java
}
override fun toType(): Class<Event> {
return Event::class.java
}
companion object {
fun create(): JSONEventConverter {
return JSONEventConverter(jacksonObjectMapper(),
SchemaMatcher.create())
}
}
}
class PostgresJSONEventBinding : Binding<Any, Event> {
override fun register(ctx: BindingRegisterContext<Event>?) {
ctx!!.statement().registerOutParameter(ctx.index(), Types.VARCHAR)
}
override fun sql(ctx: BindingSQLContext<Event>?) {
ctx!!.render().visit(DSL.`val`(ctx.convert(converter())
.value())).sql("::json")
}
override fun converter(): Converter<Any, Event> {
return JSONEventConverter.create()
}
override fun get(ctx: BindingGetResultSetContext<Event>?) {
ctx!!.convert(converter())
.value(ctx.resultSet().getString(ctx.index()))
}
override fun get(ctx: BindingGetStatementContext<Event>?) {
ctx!!.convert(converter())
.value(ctx.statement().getString(ctx.index()))
}
override fun get(ctx: BindingGetSQLInputContext<Event>?) {
throw SQLFeatureNotSupportedException()
}
override fun set(ctx: BindingSetStatementContext<Event>?) {
ctx!!.statement().setString(ctx.index(),
Objects.toString(ctx.convert(converter()).value(), null))
}
override fun set(ctx: BindingSetSQLOutputContext<Event>?) {
throw SQLFeatureNotSupportedException()
}
}
generator {
name = 'org.jooq.util.DefaultGenerator'
strategy {
name = 'org.jooq.util.DefaultGeneratorStrategy'
}
database {
name = 'org.jooq.util.postgres.PostgresDatabase'
schemata {
schema {
inputSchema = someSchema
}
schema {
inputSchema = otherSchema
}
}
forcedTypes {
forcedType {
userType = 'package.Event'
binding = 'package.PostgresJSONEventBinding'
expression = 'someSchema\\.event_store\\.event'
}
}
}
generate {
relations = true
deprecated = false
records = true
immutablePojos = true
fluentSetters = true
}
target {
packageName = appName
}
}
Is it ok to use kotlin non null types with jooq bindings?
jOOQ (or any Java library) will not respect your Kotlin non-nullable guarantees and might produce null values where you wouldn't expect them. So, perhaps it's not a good idea after all.
At the interface between jOOQ and your code, you must ensure yourself that this cannot happen.
Is this configuration ok? What should I change?
That's an open ended question. If you have any specific questions, please ask.
When I want to store value my converter gets null in from func. I don't why is that.
There are not enough infos in your question to help you about this
Ok so in my case it was about java-kotlin interoperability between nullable types in Java and non-null types in kotlin. All I had to do was implementing converter using nullable types in kotlin (the ones with ?).
Correct converter look like this:
class JSONEventConverter constructor(
private val objectMapper: ObjectMapper,
private val schemaMatcher: SchemaMatcher
) : Converter<Any, Event> {
override fun from(databaseObject: Any?): Event? {
return databaseObject?.let { schemaMatcher.parse(it.toString()) }
}
override fun to(userObject: Event?): Any? {
return userObject?.let { objectMapper.writeValueAsString(it) }
}
override fun fromType(): Class<Any> {
return Any::class.java
}
override fun toType(): Class<Event> {
return Event::class.java
}
companion object {
fun create(): JSONEventConverter {
return JSONEventConverter(serializingObjectMapper(),
SchemaMatcher.create())
}
}
}

Scope Resolution Operator in Kotlin

I have read the following syntax. I have no idea why scope resolution operator is used in it.
class XyzFragment : Fragment() {
lateinit var adapter: ChatAdapter
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
if (!::adapter.isInitialized) { <-- This one
adapter = ChatAdapter(this, arrayListOf())
}
}
}
I want to know what is :: in if (!::adapter.isInitialized) { statement.
:: is a short form for this:: in Kotlin.
:: is a operator to creates a member reference or a class reference. For example,
class Test {
fun foo() {
}
fun foo2(value: Int) {
}
fun bar() {
val fooFunction = ::foo
fooFunction.invoke() // equals to this.foo()
val foo2Function = ::foo2
foo2Function.invoke(1) // equals to this.foo2(1)
val fooFunction2 = Test::foo
val testObject = Test()
fooFunction2.invoke(this) // equals to this.foo()
fooFunction2.invoke(testObject) // equals to testObject.foo()
}
}
This is mainly used in reflection and passing function.

Configurable factory in Kotlin for JavaScript

I have a Kolin class A whose property is either supplied in a primary constructor, or is created by a factory in the secondary constructor of A.
interface I
class O : I
class A (val i: I) {
constructor(): this(factory!!.create())
}
interface Factory {
fun create(): I
}
class MyFactory: Factory {
override fun create(): I {
return O()
}
}
var factory: Factory? = null
fun main(args: Array<String>) {
factory = MyFactory()
A()
}
When I compile this code to JavaScript (Kolin Compiler version 1.0.6-release-127) and run it in a browser (Safari 10.0.3), I get the following runtime error:
ReferenceError:Can't find variable: tmp$0
The error occurs in the secondary constructor of A. It seems that Kolin has a problem in performing the null check of a parameter in the secondary constructor. The code runs correctly when I change the factory declaration to "not null" and remove the factory initialization from the main() method:
val factory: Factory = MyFactory()
fun main(args: Array<String>) {
A()
}
But this is not what I want, since I want to be able to configure the factory at application startup time.
Do I miss something, or is this a bug in Kotlin's JavaScript compiler? Does anybody know a workaround for this problem? Is there another or better way to design configurable factories in Kotlin for JavaScript?
Generated JavaScript code:
var KotlinTest = function (Kotlin) {
'use strict';
var _ = Kotlin.defineRootPackage(function () {
this.factory = null;
}, /** #lends _ */ {
I: Kotlin.createTrait(null),
O: Kotlin.createClass(function () {
return [_.I];
}, function O() {
}),
A: Kotlin.createClass(null, function A(i) {
this.i = i;
}),
A_init: function ($this) {
$this = $this || Object.create(_.A.prototype);
_.A.call($this, ((tmp$0 = _.factory) != null ? tmp$0 : Kotlin.throwNPE()).create());
return $this;
},
Factory: Kotlin.createTrait(null),
MyFactory: Kotlin.createClass(function () {
return [_.Factory];
}, function MyFactory() {
}, /** #lends _.MyFactory.prototype */ {
create: function () {
return new _.O();
}
}),
main_kand9s$: function (args) {
_.factory = new _.MyFactory();
_.A_init();
}
});
Kotlin.defineModule('KotlinTest', _);
_.main_kand9s$([]);
return _;
}(kotlin);
Answering my own question. As #marstran correctly commented, this seems to be a bug in Kolin's Javascript compiler 1.0.6 which seems to be fixed in 1.1-beta. In the meantime, I'm using a workaround similar to the following:
interface I
class O : I
class A (val i: I) {
constructor(): this(Factory.get().create())
}
interface Factory {
companion object {
private var IMPL : Factory? = null
fun get(): Factory = IMPL!!
fun set(impl: Factory) {
IMPL = impl
}
}
fun create(): I
}
class MyFactory: Factory {
override fun create(): I {
return O()
}
}
fun main(args: Array<String>) {
Factory.set(MyFactory())
A()
}