I saw one script using "value" in class constructor's parameter
BUT "val" as function parameter.
constructor(value){}
push(val){}
Is it a personal preference, or convention?
Its normal to use val in place of value as a short version.There are no such conventions. When it comes to Jquery or some other languages, val is used as a built in function name.
Related
I have a function that may take one or two parameters. In Java I would simply overload:
public myMethod( Cat cat, Dog dog){…}
public myMethod( Cat cat){…}
I understood that Kotlin has default params that would make overloading unnecessary. But these are objects for which I really know no default. So how do I proceed? And I don’t want to claim it’s nullable just for the sake of making null the default value. Any options I’m not seeing?
basically I don't want this
fun myMethod(cat:Cat, dog:Dog?=null) //it's never really nullable so don't want to pretend
I understood that Kotlin has default params that would make overloading unnecessary.
They don't; they make a specific (and very common in Java) usage of overloading unnecessary. If in Java you'd write
public myMethod(Cat cat){
myMethod(cat, new Dog(...)) // or myMethod(cat, null)
}
then in Kotlin you'd use a default argument. If you don't, then you use overloaded methods just like in Java, as mightyWOZ's answer shows.
Method (or function) overloading in kotlin works the same way as it works in java. That is you can specify multiple functions with same name but with different signature.
From Kotlin language specification
Kotlin supports function overloading, that is, the ability for several
functions of the same name to coexist in the same scope, with the
compiler picking the most suitable one when such a function is called.
So in your case if you don't want to use default parameters, then you can specify two different functions with same name but with different arguments.
So your java code can be converted to kotlin as.
fun myMethod(cat: Cat, dog: Dog){…}
fun myMethod(cat: Cat){…}
And you can call the overloaded functions as
var dog = Dog()
var cat = Cat()
myMethod(dog,cat)
myMethod(cat)
You can think as Dog is nullable in your in your Java method public myMethod( Cat cat){…}. There is no dog so it can be treated as null, since it doesn't exist. Then just check if it is null in kotlin and proceed as if it never was there.
First let's see what the Kotlin Language Documentation says:
Prefer declaring functions with default parameter values to declaring
overloaded functions.
And I don’t want to claim it’s nullable just for the sake of making
null the default value.
Then don't. So, you have to have some way of initializing dog.
You can specifiy a default value for dog right in the parameter list.
fun myMethod(cat: Cat, dog: Dog = Dog(...)) {
// ...
}
If you don't have a way of initializing dog when calling myMethod, it is not such a bad idea (as you might think) to make the parameter nullable. null means the value is absent and this is exactly the case.
fun myMethod(cat: Cat, dog: Dog? = null) {
// handle nullable dog
}
I am aware that extension functions are used in Kotlin to extend the functionality of a class (for example, one from a library or API).
However, is there any advantage, in terms of code readability/structure, by using extension functions:
class Foo { ... }
fun Foo.bar() {
// Some stuff
}
As opposed to member functions:
class Foo {
...
fun bar() {
// Some stuff
}
}
?
Is there a recommended practice?
When to use member functions
You should use member functions if all of the following apply:
The code is written originally in Kotlin
You can modify the code
The method makes sense to be able to use from any other code
When to use extension functions
You should use extension functions if any of the following apply:
The code was originally written in Java and you want to add methods written in Kotlin
You cannot change the original code
You want a special function that only makes sense for a particular part of the code
Why?
Generally, member functions are easier to find than extension functions, as they are guaranteed to be in the class they are a member of (or a super class/interface).
They also do not need to be imported into all of the code that uses them.
From my point of view, there are two compelling reasons to use extension functions:
To "extend" the behaviour of a class you're not the author of / can't change (and where inheritance doesn't make sense or isn't possible).
To provide a scope for particular functionality. For example, an extension function may be declared as a freestanding function, in which case it's usable everywhere. Or you may choose to declare it as a (private) member function of another class, in which case it's only usable from inside that class.
It sounds like #1 isn't a concern in your case, so it's really more down to #2.
Extension functions are similar to those you create as a utility functions.
A basic example would be something like this:
// Strings.kt
fun String.isEmail() : Boolean {
// check for email pattern and return true/false
}
This code can be written as a utility function in Java like this:
class StringUtils {
public static boolean isEmail(String email) {
// check for email pattern and return true/false
}
}
So what it essentially does is, calling the same function with the object you call on will be passed as the first parameter to the argument. Like the same function I have given example of in Java.
If you want to call the extension function created in kotlin from java, you need to pass the caller as the first argument. Like,
StringsKt.isEmail("example#example.com")
As per the documentation,
Extensions do not actually modify classes they extend. By defining an extension, you do not insert new members into a class, but merely make new functions callable with the dot-notation on variables of this type.
They are simply static functions with the caller as the first argument and other parameters followed by it. It just extends the ability for us to write it that way.
When to create extension functions?
When you don't have access to that class. When that class belongs to some library you have not created.
For primitive types. Int, Float, String, etc.
The another reason for using extension function is, you don't have to extend that class in order to use the methods, as if they belong to that class (but not actually part of that class).
Hope it makes a bit clear for you..
As mentioned in other answers, extension functions are primarily used in code that you can't change - maybe you want to change complex expression around some library object into easier and more readable expression.
My take would be to use extension functions for data classes. My reasoning is purely philosophical, data classes should be used only as data carriers, they shouldn't carry state and by themselves shouldn't do anything. That's why I think you should use extension function in case you need to write a function around data class.
What is the naming convention for boolean returning methods?
Using an 'is', 'has', 'should', 'can' in the front of method sound ok for some cases, but I'm not sure.
Is there a better way to name such methods?
for example: a function that checks card's validation. Should I call it isValidCard or cardValidation or another name?
(I didn't find it here: https://kotlinlang.org/docs/reference/coding-conventions.html)
Something about naming convention for properties in Kotlin, I know it's not for methods. But it's related:
From book Kotlin in Action (by Dmitry Jemerov & Svetlana Isakova) - section 2.2.1 Properties:
In Kotlin, properties are a first-class language feature, which entirely replaces fields and accessor methods.
Listing 2.5. Declaring a mutable property in a class:
class Person {
val name: String, // read only property: generates a field and a trivial getter
var isMarried: Boolean // writable property: a field, getter and a setter
}
Kotlin’s name property is exposed to Java as a getter method called
getName. The getter and setter naming rule has an exception: if the
property name starts with is, no additional prefix for the getter is
added and in the setter name, is is replaced with set. Thus, from
Java, you call isMarried().
For those using properties prefixed with can, should, etc. in mixed Kotlin/Java projects, you can also use #get:JvmName to make the generated Java method more idiomatic for Java clients.
For example, say you have a class like this:
class User(
#get:JvmName("canView")
val canView: Boolean
)
Without the annotation, Java clients would be forced to call user.getCanView(), but now they can call the more idiomatic user.canView().
Kotlin naming style assumes you use the Java naming conventions to the possible extend. I suggest you use this answer to the same question about Java.
UPDATE: they have released coding conventions
http://kotlinlang.org/docs/reference/coding-conventions.html
Methods should tell objects what to do, for example:
circle.paint()
But if I tell an object to getSomething(), I would tell the object to get "something" (from anywhere) and not to return "something", what is the typical usage of get methods (getName() would return "name").
I think that it would be more correct to name the method returnSomething().
So is get (as used typically) a bad naming pattern?
The convention probably varies depending on the language you are using, in php (which doesn't support getter/setter methods) the following is quite common:
$myObject=>setSomething($value) - sets an internal variable of $myObject representing 'something' to $value
$myObject=>getSomething() - returns an internal variable of $myObject representing 'something'
This is less common in languages like C#, which support getter/setter methods, where you'd probably do the following:
public object Something {
get { return _something; }
set { _something = value; }
}
Then you can use dot syntax to access the private variable:
myObject.Something="something";
string value=myObject.Something;
I personally don't use Get prefix.
Only prefix I do use for methods that retrieves something is Is for "indicators".
E.g. payment.IsOverdue()
As for setter methods - those shouldn't exist.
Object state should be defined by itself through invoked behavior.
Get is not necessary because when we are asking for something, nouns should be used for naming.
Deamon, first of all I think this thing kinda depends on the language.Secondly, I've got this Method Naming Guidelines for you.
The following are examples of
correctly named methods.
RemoveAll()
GetCharArray()
Invoke()
I can also say that in the company I am working we always use names like GetSomething(), GetYourAcceptRateHigher() for our methods.
I am generally not one to engage in subjective arguments over matters like variable naming, code formatting, etc. So I have no intention of starting an argument here.
I just came across this (old) blog post which recommends not prefixing member variable names:
Do not use a prefix for member
variables (_, m_, s_, etc.). If you
want to distinguish between local and
member variables you should use
"this." in C# and "Me." in VB.NET.
For C#, yeah, I get it: member variables can be lower camelCase, and public properties/methods can be PascalCase. But VB.NET is case-insensitive, so you can't really give a private member the same name as a public property except with a lower case first letter.
I've generally prefixed member variables with an underscore, but I've been told that's not idiomatic.
So really I'm just curious: how do you name your member variables in VB.NET? And is there a "standard" way?
I'm not asking because I believe there's a "right" way or because I particularly want to change my style, and certainly not because I have any desire to tell others they're "wrong." Like I said, I'm just curious.
It's personal preference, although there's widespread support for having some distinction. Even in C# I don't think there's one widely used convention.
Jeff Prosise says
As a matter of personal preference I typically prefix private fields with an underscore [in C#] ... This convention is used quite a lot in the .NET framework but it is not used throughout.
From the .NET Framework Design Guidelines 2nd Edition page 73.
Jeffrey Richter says
I make all my fields private and I prefix my instance fields with "m_" and my static fields with "s_" [in C#]
From the .NET Framework Design Guidelines 2nd Edition page 47. Anthony Moore (BCL team) also thinks using "m_" and "s_" is worth consideration, page 48.
I personally use m_ for member variables.
Although with automatic properties in VS 2010 I haven't needed to for any new code I've written recently.
I don’t like starting a line/name with an underscore since that always looks as if the line were indented by an additional space: it just makes the code unbalanced. Additionally, a lonely underscore is too inconspicuous for my taste: I prefer the identifiers to be clearly distinct.
Therefore, I periodically cycle between suffix underscore (e.g. example_) and prefix m_. I can’t decide which of those I prefer since I actually like neither. But the argument against prefix underscores partially also applies to suffix underscores.
But as you’ve remarked, some kind of distinction is necessary.
And as I’ve remarked elsewhere, I’ve had very bad experiences with case-only distinction in C# as well – it’s just too easy to confuse the names, and hence write into a private variable instead of the property. This matters if the property either checks or transforms the set value.
For that reason, I prefer to use some kind of prefix in C# as well.
I'm doing it like you.
Private _myVar as Object
Public Property MyVar() As Object
Get
Return Me._myVar
End Get
Set(ByVal value As Object)
Me._myVar = value
End Set
End Property
And in constructor
Public Sub New(myVar as object)
Me._myVar = myVar
End Sub
But I think that's a matter of taste.
The only time I use a prefix is with the private backing store for a public property. In these cases, the names are otherwise identical and most of the time the only place I'll ever reference the prefixed name is inside it's associated property. When I can finally use auto-implemented properties with VB.Net I won't even need to do that.
I do this in C# as well, on those instances when I can't just use an auto-implemented property. Better the _ prefix than varying the names only by case.
We use _ (underscore) to prefix our variables names. It's short and to the point...
Private _ID as integer
Public Property ID() As Integer
Get
Return _ID
End Get
Set(ByVal value As Integer)
_ID = value
End Set
End Property
Although a lot of the MS code seems to use m_* for private declarations, I save myself a character and just use _name for private members. My rules:
Private members are preceeded by an underscore
Public members (methods and properties) are PascalCase.
Parameters are camelCase.
Since I work in C#, having a parameter name with the same name as a property with different case is no problem. That won't work in VB, though.