Object as argument for function

object myObject{
    val fixedInt:Int =  1
    var changeableString:String="Hello World"
}
//PROBLEM
fun someFun(o:object/*<---Not working*/){
      println(o.changeableString+"  "+o.fixedInt)
      o.changeableString="Has Changed"
      println(o.changeableString+"  "+o.fixedInt)
}
someFun(myObject)

I know im using the wrong type for object, but which one is the right one?

For objects the type is the same as the name of the object so it would be fun someFun(o: myObject).


Also kotlin has a convention that all class/object names start with upper case letters so it should really be
object MyObject and fun someFun(o: MyObject) :wink:

2 Likes

Thank you very much. I though everything must be casted in a certain way.

EDIT to @Wasabi375

Didn’t help me. The problem is the function itself

```
fun someFun(o:object/*<---Not working*/){
```

It doesn’t make any sence to me to write the same function for the multible Objects

fun someFun(o:MyObject/*workes*/){}
fun someFunB(o:MyObjectB/*workes*/){}
fun someFunC(o:MyObjectC/*workes*/){}

But i need

fun someFun(o:MyObjec/*workes if the Object has the name MyObject*/){}
someFun(MyObject/*<--working*/)
someFun(MyObjectB/*<--not working*/)
someFun(MyObjectC/*<--not working*/)

I don’t understand what you’re trying to do here. The point in having a function parameter is that you can pass in different values — but in this case, there can only ever be one possible value of that type! So why not refer to it directly in the function, instead of making it a parameter?

1 Like

you mean

someFun({
var name:String="something"
var number:Int=1
})

??

Isn’t working. because, as i mentioned, wrong casting

Or are you talking about this

MyObject.somefunction()

Because i need this for a function (prototype) already

Example:

//myTextView is a TextView Element
myTextView.somefunction(MyObject)

Oh i got you. “Directly in the function”
As i’ve mentioned. I need ONE function, not the same function with different name for different Objects

You declared an object, not a new type (class or interface).

class MyObjectType { // This is not an object. This is a class
    // ...
}

In Java, all classes extend Object. In a type system, we call this the “top” of our class system since all objects inherit from it. Kotlin uses the class Any and everything extends Any.

Unlike JS, everything in Kotlin is an object. Functions are objects, Strings are objects, numbers are objects, etc.

Sometimes you will want to create some new object and not give it’s class a name to be reused elsewhere (usually because the class type is only useful in that one spot). To do this we create an anonymous object using the object keyword.

Here’s an example:

fun main() {
//sampleStart
    // Here we create a class that implements our behavior
    class CurrentTimeSentance : Sentance {
        override fun say() = println("The time is: ${System.currentTimeMillis()}")
    }
    val currentTime1 = CurrentTimeSentance()
    someFun(currentTime1)
    
    
    
    // This is an "anonymous" object.
    val currentTime2 = object : Sentance {
       override fun say() = println("The time is: ${System.currentTimeMillis()}")
    }
    someFun(currentTime2)
    
    
    
    // Here we use an anonymous object but skip declaring the variable:
    someFun(object : Sentance {
       override fun say() = println("Hello there! I am $this")
    })
//sampleEnd
}

fun someFun(o: Sentance) {
   o.say()
}

interface Sentance {
   fun say()
}

I suspect it will be much easier for you to follow a few beginner tutorials. This is only the tip of the iceberg and getting answers here on the forum will be much slower and harder to understand than the docs, video tutorials, or a book.

1 Like

I got you.

Wow, that’s why android developers earn 10 times more than web coders.
Yes, i never expected to use it as easy as all the other languages, but that is kind of weird.

In other words:
Even with an anonimous object “var myObject:something{}” i can’t use multible objects in one function, right?
So

var MyObject:something{//object}
someFun(object : soemthing) would work
var MyObjectB:something{//object}
someFun(object : something) would work too

but

var MyObject:something{//object}
var MyObjectB:something{//object}
someFun(object : soemthing) would work with MyObject only
someFun(object : something) would work with MyObject only

so MyObjectB is never called. Right?

Wow, that’s hard.

But it still has not answered my question

Forget about the objects, classes and so on.

How should i cast my argument within or for my function???

fun someFun(o:WHAT SHOULD BE HERE){}

Really, you should go through some tutorials. You have a very flawed idea of what classes, objects and types are. My guess is that you are comming from a JS/TS background which is quite different because it’s a dynamic language. Kotlin is static and strongly typed which means you need to learn quite a few new concepts.
Feel free to ask questions but as @arocnies said, there isn’t t much point without going through at least 1 tutorial first.

1 Like

Your right and i do.
But actually the object stuff itself isn’t that different

var ob=object {
            var name:String="MyName"
            var number:Int=10

        }
println(ob.name)

works as a charm (So it isn’t that different)

But that was never ever the question. Sorry for my bad english

My question was (and still is)

```
fun someFun(o:WHAT SHOULD BE HERE){}
```

That is everything. I will figure out the rest

Yes it is. The fact that you think it isn’t is the entier problem here. Just because the syntax is similar doesn’t mean that the languages work in the same way.
In typescript you can have something like:

class Foo{
    someProperty: string;
}
function foo(obj: Foo) {
    console.log(obj.someProperty)
}
foo({someProperty: "test"});

This isn’t possible in kotlin.

class Foo {
    someProperty: String
}
fun foo(obj: Foo) =  println(obj.someProperty)
val ob = object { someProperty = "test" }
foo(ob)

While the object you pass to foo might look like a Foo object it isn’t. You actually need to call the constructor. TS/JS consider something to have the same type if they have the same properties. This isn’t true in a strongly typed static language.

1 Like

So in other words, there is no such way to have an argument as an object?

So experts really do the same function for each object with another name?
How they do that on bigger projects?

I mean objects are pretty common. Is kotlin an exeption here?

Or need a class and an object.
Isn’t it easier to use a class only in first place and go from there (just read, not write)

i mean as what i’ve read on documentation it’s like

class something{
     var first:String="Hello"
    var seccond:String="World"
}
var ob:something:something()
ob.first="Hello my"

I could live with that. Is there a way to cast a class into a function?

like
fun somefun(ob:class)

I think there’s some confusion between what you’re trying to solve and what errors you’ll get trying to accomplish your goal.

fun someFun(o: Type){} // "What should be here"? The type (class or interface) should be there.

The reason @Wasabi375 and I are so highly recommending a tutorial is that a forum like this one is not very helpful to learn the basics directly. Here’s how I think about it:


Learning a new language like Kotlin is similar to learning a spoken language like English or Spanish
Right now you are in the phase of learning where you learn the letters and basic vocabulary. As you learn the letters and more words, eventually you learn the grammar rules for sentences and practice by reading easy to read books. Eventually you are reading complex books not to practice and improve your reading skills but to learn something other than the language the book is written with.

This forum is like a librarian that helps you find where you should look to answer your questions. If you ask the librarian how to spell a word, they will give you a dictionary. If you ask the librarian a complex question they will give partial input–they won’t speak a book to you but instead they will give a brief description of the book and point you to it (they also might help you ask the right questions to refine your search).

Using this analogy, you’re somewhere between learning the letters and grammar rules (possibly reading the simple books) on your way to learning Kotlin. This is a great place to be, we all were there at some point.

This is why it’s so helpful to find good learning content, docs, tutorials instead of asking your questions here. Always feel free to ask, but the answer will likely be “here are some learning resources” :slight_smile:

2 Likes

And i understand that. But unfortunately i have my ways.

And my only question was “what type or interface” should i use.

I am an beginner, but i went through tutorials which even made me make an own tutorial on Youtube for beginners by programming a TicTacToe game with AI (play against the computer)

So i know (most i guess) types. But i couldn’t find the right type for classes or objects. Not here(forum), nor kotlinlang.org, nor anywhere else.

Yes i want to learn kotlin. But for now, the cast type is everything i need. I figure out the rest, because that is my way of learning new languages. (Search, research, try and so on)

But unfortunately, for this issue i can’t find anything

And im absolutely not the kind of guy “please write my code” as you’ve seen on my other posts.
All i need is a kick in the right direction. I do the rest

And in this state of “no” knowledge i don’t mind the correct and clean way of doin it. I need a way that works to figure out why it works and how.

The point is. Kotlin is new. The documentation do not satisfy all needs right now. You need to go around a lot of corners. But im not the “Hello World” Guy.

Do you know what i mean?

And to me it’s absolutely unbelivable that there is no function argument cast for objects or even classes. Doesn’t fit to my knowledge of other languages. Because than, how does the plugins work that does exactly what i need. But i don’t want to use this plugins. Why? Exactly. I want to learn it by myself
And, by the way, those plugins are for sale by indian companies. And i don’t trust those sites

I think what’s confusing is that while many of the words are familiar to you — object, class… — some of the ideas they represent may be subtly different from what you’re used to.

(At least, so I gather — I don’t know JavaScript, so I have the opposite problem!)

Anyway, let me try to explain a few relevant things, in case it helps…

In Kotlin, everything is an object. And each object is an instance of some class. In most cases, it’s a named class — for example, "ABCDE" is an instance of the class String. And (most) named classes can have many different instances.

You define a class with the class keyword, e.g.:

class MyClass(var myField: Int) {
    // …
}

(It’s conventional to start class names with a capital letter, and function/property/parameter/variable names with a lower-class letter — you don’t have to, but it’s likely to stick out and confuse people if you don’t.)

So MyClass(1) would create a new instance of your class, and you could store it in a variable (or pass it as a parameter) whose type was MyClass.

Kotlin also allows for a special type of class which is a singleton, with only one instance. These are defined in the same way, except that they use the object keyword instead of class:

object MySingleton {
    // …
}

You can refer to this instance simply as MySingleton; but you can’t create any further instances. You could store it in a variable of type MySingleton, but there wouldn’t be any point — that variable couldn’t refer to anything else except that one instance, so you might as well just refer to it directly.

(You could also store it in a variable of type Any, which is the ultimate parent of all classes in Kotlin.)

Of course, this gets more complicated if you want your singleton object to extend another class, e.g.:

object MySingletonMyClass : MyClass(1) {
    // …
}

Here the singleton is a subclass of MyClass, so you could also store it in a variable of type MyClass — and it could make sense to do so, since there could be other instances of MyClass (or other subclasses) that it could refer to.

The third language feature which is relevant is an anonymous object. Suppose you want an extension of MyClass, but you only want to use it in one place so you don’t want to create a named class for it. You can create a one-off subclass on-the-fly:

var someVar = object : MyClass(1) {
    // …
}

This creates a variable which refers to an unnamed subclass of MyClass. It’s created as needed, but because you haven’t given the class a name, you can’t refer to its type directly. (So the variable will be of type MyClass, the nearest named type.)

In my experience, anonymous classes aren’t too common in Kotlin; they’re very handy when calling Java methods that expect you to provide an implementation of a Java interface or adapter, but in pure Kotlin such a method would be much more likely to take a function type that you can pass a lambda to instead.

2 Likes

We are circeling. Yes, i got that. And actually (e.G. for my youtube tutorial game i used classes), so i know a bit about (not yet exactly about heritage like class something : someotherclass{}) but about a single class.
I know about private, puplic and local (in kotlin there is no public, if im right each var, fun, val without a private is public) but we are absolutely missing my point. And i don’t know why. I know my english is bad, but that worse???

But Again:

If i write a function and want to use a object (or class), what type of cast, or cast of type should i use?

fun wastedTimeIGuess(myclassorobjectiwanttoreadorwrite:CAST I couldn't find the right cast but i know it's not Any, nor Int, nor,String, nor class, nor object nor nor nor){
       println("And all i need to know is the right cast to get this string "+myclassorobjectiwanttoreadorwrite.whateverstring)
} 

if there really really really is none, just tell me. Im good with that. Basically it would match my research

Oh no, you’re doing great :slight_smile: I don’t mean to suggest that you are like those people.
My point is more to let you know why you might not get a good answer here. Don’t be discouraged, it will be tough but you’ll get it :slight_smile:

Ahhhh, i think I see. You’re not asking that it should be a type, you’re asking “which type do I pick?”. Is that correct?

Well, what type does your function expect? You can’t create types on-the-fly so looking at your original example:

fun someFun(o: <WHAT SHOULD GO HERE>){
      println(o.changeableString+"  "+o.fixedInt)
      o.changeableString="Has Changed"
      println(o.changeableString+"  "+o.fixedInt)
}

Since your function calls o.changeableString, then the type should be something that has a property called changeableString.

Your original example doesn’t have any types defined. There is no class that has a property changeableString. It’s true your object has a property that happens to be named the same, but that doesn’t make it the same thing.

Just because you have a “bat” (the animal :bat:) doesn’t mean it’s the same type of thing as my “bat” (the wood stick used in sports :cricket_bat_and_ball:)
The names of properties and functions does not make a type.

1 Like

As others have pointed out it is a little tricky to help when we don’t know what you are trying to achieve. I’ll try to write some code that is close to your original post but with a function that can be called with different objects.

class MyClass(val fixedInt: Int, var changeableString: String)

val myObject = MyClass(1, "Hello World")
val myObjectB = MyClass(2, "Some text")

fun someFun(o: MyClass) {
    println(o.changeableString + "  " + o.fixedInt)
    o.changeableString = "Has Changed"
    println(o.changeableString + "  " + o.fixedInt)
}

fun main() {
    someFun(myObject)
    someFun(myObjectB)
}

Is that close to what you are trying to do?

You can’t “forget about objects, classes and so on”. The thing you have to put after the : is a class (or interface) and the object is what you pass to the function.

2 Likes

That was one of the answers i’ve asked for. It was answered similar before, but unfortunately not in that really good understandable version. Havent tried it yet, because im answering to you, but this really make sence to me

So this should work, right?

class myfunctionkindofobject{
      var name:String ="I am a string"

}
fun myfunction(o:myfunctionkindofobject){
      println(o.name)
     //should print "I am a string and i was changed"
}
var l:myfunctionkindofobject = myfunctionkindofobject();
l.name="I am a string and i was changed"
myfunction(l)

If so, not the perfect solution, because i have to declare each var for my needs (in some cases some will be null, so i have to use “maybe --?–”, but that would help me at least for my current project.

So thank you

Yes, that works and prints what you expect.

Isn’t there any way to add some variables to an existing class like

[code]
class someClass{
}
var call:someClass=someClass()
call.unknownvar:String = “Im new to class”
println(call.unknownvar)

[code]

Sorry, could’nt check it by myself yet as Android studio is updateting.