https://kotlinlang.org logo
Title
a

AmrJyniat

07/15/2022, 8:29 AM
Can I have one abstract fun with multiple parameters/constructor without asking me to override two funs in the inherited class?, like so:
abstract class A {
   abstract foo(param1: Any): Any
   abstract foo(param1: Any, param2, Any): Any
}

class B: A {
   //ask me to override one fun at lease and make the other fun optional
   override foo(param1: Any): Any {
     ......
   }
}
I'll always inject the
foo()
fun with all parameters, but I don't need them in the inherited class in most cases
u

uli

07/16/2022, 7:49 AM
Hi, what do you expect to happen if the not overridden fun ever gets called? The compiler can not prevent that, as you declared B to implement A which is a guarantee that all methods of A are available. If you can live without the help of the compiler you can implement on of the foos in A to throw an exception. This implementation will then be used if you don't override
a

AmrJyniat

07/16/2022, 7:58 AM
In other words, is there a way to make some parameters optional inside the override fun?
override foo(
   param1: Any,
   param2: Any //Optional to being here
): Any {
     ......
}
u

uli

07/16/2022, 8:03 AM
You can give it a default value. Maybe null
Please let us know the behavior you are looking for. What should happen if the optional parameter if not provided?
Best would be if you explain a bit what foo is and give an example
a

AmrJyniat

07/16/2022, 8:07 AM
I'll provide the param always inside the abstract class, but I don't need it always in the overridden fun
u

uli

07/16/2022, 8:08 AM
Can't you just ignore it?
a

AmrJyniat

07/16/2022, 8:08 AM
No because I need it in some cases
I think default value will works as you said, let me try, Thanks man
u

uli

07/16/2022, 8:10 AM
A could provide a default implementation:
fun foo(a:Any,b:Any)=foo(a)
And on a side note, this channel is for kotlin native related stuff. Kotlin native is about compiling kotlin to native machine code like Linux Mac Windows and ios. Next time please ask in #general-advice
👍 1