пятница, 2 апреля 2021 г.

Types

void main() {

  //Mutable - Explicit annotation
  dynamic dyn = false; // can be any! type
  num n1 = 1; //num
  n1 = 1.0; // can be int or double
  int i1 = 1; //integer
  double d1 = 1.0; //double
  bool b1 = true; //boolean
  String s1 = 'text'; //String

  //Immutable - Explicit annotation
  const int i2 = 2; // compile time const
  final double d2 = 2.0; // runtime const

  //Inference - Mutable and Immutable
  var i3 = 3; // int
  const d3 = 3.0; // double const
  final s2 = 'UserInput'; // String const

  //Runtime type check - runtimeType, is
  print('${i3.runtimeType} is integer: ${i3 is int}');

  //Conversion
  var d4 = i3.toDouble();
  print(d4.toStringAsFixed(2)); // two decimal places
  var i4 = d4.toInt(); // loss of precision
  print(i4.runtimeType); // int

  //Promotion
  var d5 = i4 * d4; // int * double = double
  var i5 = (i4 * d4).toInt(); // int
  double d6 = 3; // double

  //Down casting - as
  //superclass to subclass, num to int or double
  print((n1 as double).truncate());
  //if promote down casting
  if (n1 is double){
    n1.round();
  }

  //Object type
  Object? o1; // General (super) type for all types
  print(o1.runtimeType); // Null
  //OOP - Inheritance
  o1 = 24; // int
  o1 = 32.0; // double
  o1 = 'text'; // String

}

Комментариев нет:

Отправить комментарий