# Object as argument for function

**URL:** <https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612>\
**Category:** Uncategorized\
**Created:** [October 22, 2020, 9:01pm UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612 "2020-10-22T21:01:44Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![absoluterookie](https://avatars.discourse-cdn.com/v4/letter/a/f17d59/32.png) [@absoluterookie](https://discuss.kotlinlang.org/u/absoluterookie)\
**Post date:** [October 22, 2020, 9:01pm UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612/1 "2020-10-22T21:01:44Z")

</div>

```auto
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?

---

<div class="post-metadata">

**Author:** ![Wasabi375](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/wasabi375/32/4741_2.png) [@Wasabi375](https://discuss.kotlinlang.org/u/Wasabi375)\
**Post date:** [October 22, 2020, 9:08pm UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612/2 "2020-10-22T21:08:07Z")

</div>

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)` 😉

---

<div class="post-metadata">

**Author:** ![absoluterookie](https://avatars.discourse-cdn.com/v4/letter/a/f17d59/32.png) [@absoluterookie](https://discuss.kotlinlang.org/u/absoluterookie)\
**Post date:** [October 22, 2020, 9:09pm UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612/3 "2020-10-22T21:09:10Z")

</div>

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

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

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

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

But i need

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

---

<div class="post-metadata">

**Author:** ![gidds](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/gidds/32/10865_2.png) [@gidds](https://discuss.kotlinlang.org/u/gidds)\
**Post date:** [October 22, 2020, 9:38pm UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612/4 "2020-10-22T21:38:43Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![absoluterookie](https://avatars.discourse-cdn.com/v4/letter/a/f17d59/32.png) [@absoluterookie](https://discuss.kotlinlang.org/u/absoluterookie)\
**Post date:** [October 22, 2020, 9:40pm UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612/5 "2020-10-22T21:40:41Z")

</div>

you mean

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

??

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

Or are you talking about this

```auto
MyObject.somefunction()
```

Because i need this for a function (prototype) already

Example:

```auto
//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

---

<div class="post-metadata">

**Author:** ![arocnies](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/arocnies/32/5143_2.png) [@arocnies](https://discuss.kotlinlang.org/u/arocnies)\
**Post date:** [October 22, 2020, 9:48pm UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612/6 "2020-10-22T21:48:58Z")

</div>

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

```kotlin
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](https://kotlinlang.org/docs/reference/object-declarations.html) using the `object` keyword.

Here’s an example:

```run-kotlin
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](https://www.atomickotlin.com/).

---

<div class="post-metadata">

**Author:** ![absoluterookie](https://avatars.discourse-cdn.com/v4/letter/a/f17d59/32.png) [@absoluterookie](https://discuss.kotlinlang.org/u/absoluterookie)\
**Post date:** [October 22, 2020, 10:02pm UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612/7 "2020-10-22T22:02:18Z")

</div>

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

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

but

```auto
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???

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

---

<div class="post-metadata">

**Author:** ![Wasabi375](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/wasabi375/32/4741_2.png) [@Wasabi375](https://discuss.kotlinlang.org/u/Wasabi375)\
**Post date:** [October 22, 2020, 10:16pm UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612/8 "2020-10-22T22:16:12Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![absoluterookie](https://avatars.discourse-cdn.com/v4/letter/a/f17d59/32.png) [@absoluterookie](https://discuss.kotlinlang.org/u/absoluterookie)\
**Post date:** [October 22, 2020, 10:19pm UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612/9 "2020-10-22T22:19:40Z")

</div>

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

```auto
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)

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

That is everything. I will figure out the rest

---

<div class="post-metadata">

**Author:** ![Wasabi375](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/wasabi375/32/4741_2.png) [@Wasabi375](https://discuss.kotlinlang.org/u/Wasabi375)\
**Post date:** [October 22, 2020, 10:38pm UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612/10 "2020-10-22T22:38:21Z")

</div>

> [@absoluterookie](#):
>
> But actually the object stuff itself isn’t that different

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:

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

```

This isn’t possible in kotlin.

```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.

---

<div class="post-metadata">

**Author:** ![absoluterookie](https://avatars.discourse-cdn.com/v4/letter/a/f17d59/32.png) [@absoluterookie](https://discuss.kotlinlang.org/u/absoluterookie)\
**Post date:** [October 22, 2020, 10:43pm UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612/11 "2020-10-22T22:43:21Z")

</div>

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

```auto
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)

---

<div class="post-metadata">

**Author:** ![arocnies](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/arocnies/32/5143_2.png) [@arocnies](https://discuss.kotlinlang.org/u/arocnies)\
**Post date:** [October 22, 2020, 11:04pm UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612/12 "2020-10-22T23:04:23Z")

</div>

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

```auto
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” 🙂

---

<div class="post-metadata">

**Author:** ![absoluterookie](https://avatars.discourse-cdn.com/v4/letter/a/f17d59/32.png) [@absoluterookie](https://discuss.kotlinlang.org/u/absoluterookie)\
**Post date:** [October 22, 2020, 11:09pm UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612/13 "2020-10-22T23:09:36Z")

</div>

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](http://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

---

<div class="post-metadata">

**Author:** ![gidds](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/gidds/32/10865_2.png) [@gidds](https://discuss.kotlinlang.org/u/gidds)\
**Post date:** [October 22, 2020, 11:31pm UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612/14 "2020-10-22T23:31:29Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![absoluterookie](https://avatars.discourse-cdn.com/v4/letter/a/f17d59/32.png) [@absoluterookie](https://discuss.kotlinlang.org/u/absoluterookie)\
**Post date:** [October 22, 2020, 11:40pm UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612/15 "2020-10-22T23:40:43Z")

</div>

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?

```auto
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

---

<div class="post-metadata">

**Author:** ![arocnies](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/arocnies/32/5143_2.png) [@arocnies](https://discuss.kotlinlang.org/u/arocnies)\
**Post date:** [October 22, 2020, 11:50pm UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612/16 "2020-10-22T23:50:17Z")

</div>

> [@absoluterookie](#):
>
> 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

Oh no, you’re doing great 🙂 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 🙂

> [@absoluterookie](#):
>
> If i wright a function and want to use a object (or class), what type of cast, or cast of type should i use?

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:

```kotlin
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 🦇) doesn’t mean it’s the same type of thing as my “bat” (the wood stick used in sports 🏏)  
The names of properties and functions does not make a type.

---

<div class="post-metadata">

**Author:** ![christofferberg79](https://avatars.discourse-cdn.com/v4/letter/c/c0e974/32.png) [@christofferberg79](https://discuss.kotlinlang.org/u/christofferberg79)\
**Post date:** [October 22, 2020, 11:51pm UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612/17 "2020-10-22T23:51:11Z")

</div>

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.

```auto
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.

---

<div class="post-metadata">

**Author:** ![absoluterookie](https://avatars.discourse-cdn.com/v4/letter/a/f17d59/32.png) [@absoluterookie](https://discuss.kotlinlang.org/u/absoluterookie)\
**Post date:** [October 22, 2020, 11:59pm UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612/18 "2020-10-22T23:59:15Z")

</div>

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?

```auto
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

---

<div class="post-metadata">

**Author:** ![christofferberg79](https://avatars.discourse-cdn.com/v4/letter/c/c0e974/32.png) [@christofferberg79](https://discuss.kotlinlang.org/u/christofferberg79)\
**Post date:** [October 23, 2020, 12:08am UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612/19 "2020-10-23T00:08:34Z")

</div>

Yes, that works and prints what you expect.

---

<div class="post-metadata">

**Author:** ![absoluterookie](https://avatars.discourse-cdn.com/v4/letter/a/f17d59/32.png) [@absoluterookie](https://discuss.kotlinlang.org/u/absoluterookie)\
**Post date:** [October 23, 2020, 12:10am UTC](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612/20 "2020-10-23T00:10:27Z")

</div>

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.

[Next page](https://discuss.kotlinlang.org/t/object-as-argument-for-function/19612.md?page=2)
