C# ile Kotlin Sözdizimi Karşılaştırmalarını Tamamlayın

giriiş
Bir C# geliştiricisiyseniz ve Kotlin’de yeniyseniz bu makale tam size göre. C# ve Kotlin arasındaki sözdizimi karşılaştırmalarına hızlı bir genel bakış sunar. Ayrıca Kotlin sözdizimi için hızlı başvuru kılavuzunuz olarak da sunulabilir.
Lütfen bu 2 dil için standart adlandırma kurallarının ve kodlama stillerinin de farklı olduğunu unutmayın. Aşağıdaki kod örneklerinde farkları görebilirsiniz.
Kotlin sözdizimini anlamakta zorluk çekiyorsanız, lütfen aşağıdaki örneklere bakın. kotlinlang.org .
Yöntemler ve İşlevler
C#
public virtual void PrintMessageWithPrefix(
String message,
String prefix = "Info")
{
Console.WriteLine($"{prefix} {message}");
}
Kotlin
fun printMessageWithPrefix(
message: String,
prefix: String = "Info") {
println("[$prefix] $message")
}
Görünürlük değiştirici Kotlin’de belirtilmemişse, public
ve virtual
varsayılan olarak.
Değişkenler
C#
string a = "initial";
const int b = 1;
const int c = 3;
Kotlin
var a: String = "initial"
val b: Int = 1
val c = 3
İkisi birden var
C# ve Kotlin’de benzerdir. yok val
C# kavramı. En yakın şey const
ve readonly
.
Sıfır Güvenlik
C#
string nullable = "You can keep a null here";
nullable = null
Kotlin
var neverNull: String = "This can't be null"
neverNull = null
var nullable: String? = "You can keep a null here"
nullable = null
C#’da Null Safety yoktur. Kotlin’de, siz belirtmediğiniz sürece değişken varsayılan olarak null olamaz ?
değişken bildiriminizde.
sınıflar
C#
public class Contact
{
public int id;
public string email;
public Contact(int id, string email)
{
this.id = id;
this.email = email;
}
}
Kotlin
class Contact(val id: Int, var email: String)
Kotlin’in ne kadar muhteşem olduğunu görebiliyor musunuz?
jenerik
C#
public class GenericList<T>
{
public void Add (T data)
{
}
}
public GenericList<T> CreateGenericList<T>()
{
return new GenericList<T>();
}
Kotlin
class GenericList<T>() {
fun add (data: T) {
}
}
fun <T> createGenericList() = GenericList<T>()
Miras
C#
public class Dog
{
public virtual void SayHello()
{
Console.WriteLine("wow wow!");
}
}
public class Yorkshire : Dog
{
public override void SayHello()
{
Console.WriteLine("wif wif!");
}
}
Kotlin
open class Dog {
open fun sayHello() {
println("wow wow!")
}
}
class Yorkshire : Dog() {
override fun sayHello() {
println("wif wif!")
}
}
Kotlin’in sınıfları ve işlevleri final
ve virtual
varsayılan olarak. open
devralmaya izin vermek için değiştirici gereklidir.
Switch vs When İfadesi
C#
void SwitchFunction(int input)
{
switch (input)
{
case 0:
break;
default:
break;
}
}
Kotlin
fun SwitchFunction(input: Int) {
when (input) {
0 -> {
}
else -> {
}
}
}
Geçiş ve Ne Zaman İfadesi
C#
var input = 1;
var output = input switch
{
1 => "one",
2 => "two",
_ => "too big",
};
Kotlin
val input = 1
val output = when (input) {
1 -> "one"
2 -> "two"
else -> "too big"
}
döngüler
C#
var cakes = new List<String>() { "carrot", "cheese", "chocolate" };
foreach (var cake in cakes)
{
Console.WriteLine($"Yummy, it's a {cake} cake!");
}
var cakesEaten = 0;
while (cakesEaten < cakes.Count)
{
++cakesEaten;
}
cakesEaten = 0;
do
{
++cakesEaten;
} while (cakesEaten < cakes.Count);
Kotlin
val cakes = listOf("carrot", "cheese", "chocolate")
for (cake in cakes) {
println("Yummy, it's a $cake cake!")
}
var cakesEaten = 0
while (cakesEaten < cakes.size) {
++cakesEaten
}
cakesEaten = 0
do {
++cakesEaten
} while (cakesEaten < cakes.size)
Aralıklar
C#
foreach (var index in Enumerable.Range(1, 5))
{
Console.WriteLine(index);
}
Kotlin
for(index in 1..5) {
print(index)
}
Eşitlik Kontrolleri
C#
var authors = new HashSet<string>()
{ "Shakespeare", "Hemingway", "Twain" };
var writers = new HashSet<string>()
{ "Twain", "Shakespeare", "Hemingway" };
Console.WriteLine(authors.SetEquals(writers));
Console.WriteLine(authors == writers);
Kotlin
val authors = setOf("Shakespeare", "Hemingway", "Twain")
val writers = setOf("Twain", "Shakespeare", "Hemingway")
println(authors == writers)
println(authors === writers)
Burada önemli olan ==
Kotlin’de yapısal bir karşılaştırma ve ===
referans karşılaştırmasıdır. C#’da, ==
(benzer Equals()
API) referans karşılaştırmasıdır. C#’da yapısal karşılaştırma için çağrılacak API’yi belirtin (örn. SetEquals()
) yukarıdaki örnekte olduğu gibi.
Koşullu İfade
C#
int Max(int a, int b) => a > b ? a : b;
Console.WriteLine(Max(99, -42));
Kotlin
fun max(a: Int, b: Int) = if (a > b) a else b
println(max(99, -42))
Üçlü operatör yok condition ? then : else
Kotlin’de.
Kayıt ve Veri Sınıfları Karşılaştırması
C#
public record User{
public int Id { get; set; }
public string Name { get; set; }
}
Kotlin
data class User(val id: Int, val name: String) {
}
Enum Sınıfları
C#
enum State
{
IDLE, RUNNING, FINISHED
}
Kotlin
enum class State {
IDLE, RUNNING, FINISHED
}
Mühürlü Sınıflar
C#
public sealed class Mammal {}
Kotlin
sealed class Mammal()
benzerleri var ama sealed class
Kotlin’de hala aynı paket içinde olduğu sürece alt sınıflamanıza izin verir. C#’da sealed
tüm senaryolarda %100 kapalı anlamına gelir.
Statik ve Nesne Anahtar Kelimesi
C#
public class DayRates
{
int standard = 30;
}
var dayRates = new DayRates();
static class DoAuth
{
static void DoSomething()
{
}
}
class Server
{
static class DoAuth
{
static void DoSomething()
{
}
}
}
Kotlin
val dayRates = object {
var standard: Int = 30
}
object DoAuth {
fun doSomething() {
}
}
class Server {
companion object DoAuth {
fun doSomething() {
}
}
}
Güncelleme: 21 Mayıs 2022 – Aşağıdaki makale nasıl olduğunu gösterir object
anahtar kelime, çok sayıda ortak kod kodunu azaltabilir.
Üst Düzey Yöntemler / Fonksiyonlar
C#
public int Calculate(int x, int y, Func<int, int, int> operation)
{
return operation(x, y);
}
public int Sum(int x, int y)
{
return x + y;
}
int sumResult = Calculate(1, 2, Sum)
Kotlin
fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {
return operation(x, y)
}
fun sum(x: Int, y: Int) = x + y
val sumResult = calculate(1, 2, ::sum)
Lambda Yöntemleri / Fonksiyonları
C#
Func<String, String> UpperCase
= (String str) => { return str.ToUpper(); };
Kotlin
val upperCase = { str: String -> str.uppercase() }
Uzatma Yöntemleri / İşlevleri
C#
public static class Extensions
{
public static bool IsBig(this int value)
{
return value > 100;
}
}
int value = 1000;
Console.WriteLine(value.IsBig());
Kotlin
fun Int.isBig() :Boolean {
return this > 100
}
val value = 1000
println(value.isBig())
Liste / IReadOnlyList ve MutableList / Liste
C#
List<int> systemUsers = new List<int> { 1, 2, 3 };
IReadOnlyList<int> sudoers = new List<int> { 1, 2, 3 };
Kotlin
val systemUsers: MutableList<Int> = mutableListOf(1, 2, 3)
val sudoers: List<Int> = systemUsers
Kotlin List
varsayılan olarak değişmezdir ve C#List
varsayılan olarak değişkendir.
HashSet / ImmutableHashSet vs MutableSet / Set
C#
var openIssues = new HashSet< String>
{ "uniqueDescr1", "uniqueDescr2", "uniqueDescr3"};
var immutableOpenIssues = ImmutableHashSet.Create<String>();
immutableOpenIssues.Add("uniqueDescr1");
immutableOpenIssues.Add("uniqueDescr2");
immutableOpenIssues.Add("uniqueDescr3");
Kotlin
val openIssues: MutableSet<String> = mutableSetOf(
"uniqueDescr1", "uniqueDescr2", "uniqueDescr3")
val immutableOpenIssues: Set<String> = setOf(
"uniqueDescr1", "uniqueDescr2", "uniqueDescr3")
IReadOnlyDictionary / Sözlük ve Harita / MutableMap
C#
IReadOnlyDictionary<string, string> occupations =
new Dictionary<string, string>
{
["Malcolm"] = "Captain",
["Kaylee"] = "Mechanic"
};
var occupationsMutable = new Dictionary<string, string>
{
["Malcolm"] = "Captain",
["Kaylee"] = "Mechanic"
};
Kotlin
val occupations = mapOf(
"Malcolm" to "Captain",
"Kaylee" to "Mechanic" )
val occupationsMutable = mutableMapOf(
"Malcolm" to "Captain",
"Kaylee" to "Mechanic" )
nerede vs filtre
C#
var numbers = new List<int> { 1, -2, 3, -4, 5, -6 };
var positives = numbers.Where(x => x > 0);
var negatives = numbers.Where(x => x < 0);
Kotlin
val numbers = listOf(1, -2, 3, -4, 5, -6)
val positives = numbers.filter { x -> x > 0 }
val negatives = numbers.filter { it < 0 }
Haritaya karşı seçin
C#
var numbers = new List<int> { 1, -2, 3, -4, 5, -6 };
var doubled = (List<int>)numbers.Select(x => x * 2);
Kotlin
val numbers = listOf(1, -2, 3, -4, 5, -6)
val doubled = numbers.map { x -> x * 2 }
Lütfen bunu not al map
ve Map
farklıdır. Map
bir sözlük koleksiyonudur ve map
koleksiyonun uzantı işlevleridir.
herhangi biri, tümü, hiçbiri vb.
C#
var numbers = new List<int> { 1, -2, 3, -4, 5, -6 };
var anyNegative = numbers.Any(x => x < 0);
var allEven = numbers.All(x => x % 2 == 0);
var allOdd = numbers.All(x => x % 2 != 0);
Kotlin
val numbers = listOf(1, -2, 3, -4, 5, -6)
val anyNegative = numbers.any { it < 0 }
val allEven = numbers.all { it % 2 == 0 }
val allOdd = numbers.none { it % 2 == 0 }
none
C#’da mevcut değil ama aynı sonucu şu şekilde de elde edebilirsiniz: All
Hepsini burada listelemediğim başka benzer uzantı işlevleri de var. find
, findAll
, first
, last
, count
, associateBy
, groupBy
, partition
, flatMap
, minOrNull
, maxOrNull
, sorted
, []
– harita öğesi erişimi, zip
ve getOrElse
. C#, eşdeğer işlevlere sahip olabilir veya olmayabilir.
izin ver, koş, uygula, ayrıca
C#
public void CustomPrint(String str)
{
Console.WriteLine($"Custom: {str}");
}
var myStr = "test";
CustomPrint(myStr);
var empty = myStr.Length == 0;
Kotlin
fun customPrint(str: String) {
println("Custom: $str")
}
var myStr = "test"
var empty = myStr.let {
customPrint(it)
it.isEmpty()
}
empty = myStr.run {
customPrint(this)
isEmpty()
}
empty = with(myStr) {
customPrint(this)
isEmpty()
}
empty = myStr.apply {
customPrint(this)
}.isEmpty()
empty = myStr.also {
customPrint(it)
}.isEmpty()
C#’da kapsam yöntemi yoktur ve gerekirse özel uygulamaya ihtiyacı vardır.
Gördüğünüz gibi, bu kapsam işlevleri çok benzer. Aslında, bence değiştirilebilir. Bunları nasıl kullanacağımı %100 bilmiyorum. Ancak, bunların nasıl kullanılacağına dair kurallar olduğunu düşünüyorum (başka bir blog gönderisinde ele alınacaktır).
Güncelleme: 11 Oca 2022 – Kullanım önerilerim için aşağıdaki makaleye bakın:
tembel tarafından – Temsil Edilen Özellikler
C#
string lazyStr = null;
public string LazyStr
{
get
{
if (lazyStr == null)
{
Console.WriteLine("computed!");
lazyStr = "my Lazy";
}
return lazyStr;
}
}
Kotlin
val lazyStr: String by lazy {
println("computed!")
"my lazy"
}
Özet
Bence Kotlin, C#’tan daha güçlü. Kazan plakası kodunun kullanımını azaltır. C# aynı şeyi daha fazla kodla başarabilir. Umarım bu karşılaştırmalar yardımcı olur.