Object quick inheritance and Interface meaning - object

I find in Kotlin: Object documentation an example:
open class A(x: Int) {
public open val y: Int = x
}
interface B {...}
val ab: A = object : A(1), B {
override val y = 15
}
So I implemented that example with more meaningful names and I have no clue what is the reason of the interface among the comma separated list of supertypes to the object?
interface Toy {
fun play () {
println("Play, play....")
}
}
open class Ball(public open val color: String = "red") {}
val ball: Ball = object : Ball(), Toy {
override val color : String = "blue"
override fun play() {
println("Bounce, bounce...")
}
}
fun main(args: Array<String>) {
println(ball.color)
// no ball.play() here then why the interface in the example ???
}

You're correct, the interface B (or in your example, Toy) will not be directly accessible through this reference if A (or Ball) doesn't implement it.
Inheriting from that interface is probably just added here so that this example intended to show how constructor parameters are passed to a superclass can also show off inheriting from multiple types very quickly. Or at least that's what I gather from the text accompanying it:
If a supertype has a constructor, appropriate constructor parameters must be passed to it. Many supertypes may be specified as a comma-separated list after the colon.
To get to the issue of not being able to use the created object as a B (or Toy) here: this doesn't make the language feature useless, since the created object can still be used through its multiple interfaces through casting. For example, in your example, you can do this:
(ball as Toy).play()
Or in the original example, you could make the type Any, and then cast to the different interfaces as needed.

You have created an instance of an anonymous class that inherits from class Ball and at the same time implements interface Toy.
But, both of these types are exclusive, ie. Ball is not a Toy (in your example), so you cannot call play() on a reference to Ball.

Related

How recognize between function call and class instantiation in IntelliJ or Android Studio?

I learn Kotlin in Android, but many codes are scrap because I have problem recognize when is some code as call function or instantiate class.
Code not work, but for example is good:
class Boo{
val callFromFoo: Int = Foo(1)
val instanceFoo: Foo = Foo(2)
fun Foo(id: Int): Int {
return id
}
}
class Foo(val id: Int)
I'm concerned, because call Foo(1) and instantiating Foo(2) is the same code, without IDE recognizing of differences.
Note: explicit declaration is not standard in Kotlin.
If you have the classes within the same file/package you could use reflection like so:
class Boo {
val callFromFoo: Int = Foo(1)
val instanceFoo: Foo = requireNotNull(Foo::class.primaryConstructor).call(2)
fun Foo(id: Int): Int {
return id
}
}
class Foo(val id: Int)
If you have the classes in different packages, you could instantiate the object specifying that package. Like so:
class Boo {
val callFromFoo: Int = Foo(1)
val instanceFoo: Foo = com.android.example.package2.Foo(2)
fun Foo(id: Int): Int {
return id
}
}
I would not recommend either of those solutions.
Note that classes are generally nouns like Navigator, LoginUseCase, User, Logger etc and functions are generally verbs or atleast use verbs like navigateTo(), login(), processData(), log() etc. I don`t think they should ever have the same name.
Furthermore, I think the coding style you are using does not go well with Kotlin. It will create unnecessary confusion between functions and classes even if they have different names. I suggest you follow the official Kotlin coding style guide. Have function names start with lower case and class names start with upper case to avoid any confusion.
Update
If you would like to stick to your coding convention and differentiate between constructor call and function call, you could choose varying colors for each in Android Studio or IntelliJ.
Android Studio/IntelliJ:
File > Settings > Editor > Color scheme > Kotlin
Result:

How to draw UML diagrams passing parameters through super constructor

I have a superclass called A and a subclass called B that inherits from A. The superclass's constructor looks like this:
A(String name, char displayChar, int hitPoints, Behaviour behaviour)
{
this.name = name;
this.displayChar = displayChar;
this.hitPoints = hitPoints
addBehaviour(behaviour);
}
A has attributes of name, displayChar, hitPoints, behaviour and has a method that calls addBehaviour which adds the behaviour to the object.
The subclass, B's constructor looks like this:
B(String name) {super(name, char 'b', 10, new WalkBehaviour()); }
Now my question is, does subclass B have an attribute of WalkBehaviour?
How would the UML diagram look like for this scenario? I know B inherits from A and A has Behaviour but does B has WalkBehaviour in this case? Since B doesn't have an instance variable of type WalkBehaviour in its class but only passes WalkBehaviour through its superclass's constructor.
does subclass B have an attribute of WalkBehaviour?
No. There is none declared. The superclass will do something with that new object but obviously it's hidden in the mist of its implementation.
Inheritance is nothing that involves multiple object creation. Your B instance is just a single one which does have attributes and operations like its super class.
Thus, in a SD, you will see only one life line for B:
As you can see the B instance will just issue a self-call to the super class's constructor.
Note: as #AxelScheithauer pointed out in the comment the super class will invoke addBehavior which can (but must not) be shown in the SD:

C# cannot implicitly convert type when types are the same

I have a generic class:
public abstract class ModelSet<T> : ObservableCollection<T>, IModelObject where T : ModelObject, new(){
public static ModelSet<T> Lookup(long pObjectId){
return (ModelObjectMap.Get(pObjectId) as ModelSet<T>);
}
}
I have the following class instantiation of the type using a class Movement defined as:
class Movement : ModelObject.
public partial class Movements : ModelSet<Movement>
The following code won't compile due to
cannot implicitly convert type ModelSet<Movement> to Movements. An explicit conversion exists.
Movements X = Movements.Lookup(12345);
Surely, they are the same. What am I doing wrong?
Surely, they are the same.
No, they're not the same. One is Movements, and the other is ModelSet<Movement>. While every Movements instance is an instance of ModelSet<Movement>, it's entirely possible to have a ModelSet<Movement> which isn't a Movements... and your method's return type only says that it will return a ModelSet<T>.
We have no idea what ModelObjectMap.Get(pObjectId) actually does, but it could definitely return a ModelSet<Movement> instance which isn't a Movements.
We don't know what you need to do with the return value, but you could certainly write:
ModelSet<Movement> X = Movements.Lookup(12345);
... although it's worth noting that the Movements class actually isn't involved in that call at all; it would actually be compiled to:
ModelSet<Movement> X = ModelSet<Movement>.Lookup(12345);

Groovy named and default arguments

Groovy supports both default, and named arguments. I just dont see them working together.
I need some classes to support construction using simple non named arguments, and using named arguments like below:
def a1 = new A(2)
def a2 = new A(a: 200, b: "non default")
class A extends SomeBase {
def props
A(a=1, b="str") {
_init(a, b)
}
A(args) {
// use the values in the args map:
_init(args.a, args.b)
props = args
}
private _init(a, b) {
}
}
Is it generally good practice to support both at the same time? Is the above code the only way to it?
The given code will cause some problems. In particular, it'll generate two constructors with a single Object parameter. The first constructor generates bytecode equivalent to:
A() // a,b both default
A(Object) // a set, b default
A(Object, Object) // pass in both
The second generates this:
A(Object) // accepts any object
You can get around this problem by adding some types. Even though groovy has dynamic typing, the type declarations in methods and constructors still matter. For example:
A(int a = 1, String b = "str") { ... }
A(Map args) { ... }
As for good practices, I'd simply use one of the groovy.transform.Canonical or groovy.transform.TupleConstructor annotations. They will provide correct property map and positional parameter constructors automatically. TupleConstructor provides the constructors only, Canonical applies some other best practices with regards to equals, hashCode, and toString.

Accessing type members outside the class in Scala

I am trying to understand type members in Scala. I wrote a simple example that tries to explain my question.
First, I created two classes for types:
class BaseclassForTypes
class OwnType extends BaseclassForTypes
Then, I defined an abstract type member in trait and then defined the type member in a concerete class:
trait ScalaTypesTest {
type T <: BaseclassForTypes
def returnType: T
}
class ScalaTypesTestImpl extends ScalaTypesTest {
type T = OwnType
override def returnType: T = {
new T
}
}
Then, I want to access the type member (yes, the type is not needed here, but this explains my question). Both examples work.
Solution 1. Declaring the type, but the problem here is that it does not use the type member and the type information is duplicated (caller and callee).
val typeTest = new ScalaTypesTestImpl
val typeObject:OwnType = typeTest.returnType // declare the type second time here
true must beTrue
Solution 2. Initializing the class and using the type through the object. I don't like this, since the class needs to be initialized
val typeTest = new ScalaTypesTestImpl
val typeObject:typeTest.T = typeTest.returnType // through an instance
true must beTrue
So, is there a better way of doing this or are type members meant to be used only with the internal implementation of a class?
You can use ScalaTypesTestImpl#T instead of typeTest.T, or
val typeTest:ScalaTypesTest = new ScalaTypesTestImpl
val typeObject:ScalaTypesTest#T = typeTest.returnType
If you don't want to instance ScalaTypesTestImpl, then, perhaps, you'd be better off putting T on an object instead of class. For each instance x of ScalaTypesTestImpl, x.T is a different type. Or, in other words, if you have two instances x and y, then x.T is not the same type as y.T.

Resources