lmkaonthego.blogg.se

Java to kotlin converter
Java to kotlin converter






java to kotlin converter

If an adapter is found that can be used for the requested conversion we call adaptTo(.) of the adapter and return the result. : Exception("No suitable adapter found to convert $from to type $to") ?: throw NoSuitableAdapterFoundException(this, T::class)Ĭlass NoSuitableAdapterFoundException(from: Any, to: KClass) Within the extension function we can now search the adapters list for a suitable adapter: So, we create a simple list that stores our adapter implementations: Our adaptTo() extension function needs a way to access available adapters. We use a simple Adapter interface for this:įun  canAdapt(from: Any, to: KClass): BooleanĬanAdapt(.) returns true when the implementing class is able to convert the from object to type to.ĪdaptTo(.) performs the actual conversion and returns an object of type to. In order to implement the adaptTo() method we need a way to define conversion rules. Val b = a.adaptTo() Providing conversion rules with adapters We keep the method body empty for the moment.Ĭonverting an Object of type A to another object of type B will look like this with our new method: The generic parameter T parameter specifies the target type that should be returned by the method. The following declaration adds an adaptTo() method to all sub types of Any. With Kotlins extension functions we can add methods to existing classes. We will implement a very similar approach in Kotlin. In this case, you are probably familiar with Slings usage of adapters. In this post we will learn how we can use Kotlin extension functions to provide a simple and elegant type conversion mechanism.








Java to kotlin converter